通过Node中的“_id”搜索MongoDB条目的正确方法 [英] Correct way to search for MongoDB entries by '_id' in Node

查看:115
本文介绍了通过Node中的“_id”搜索MongoDB条目的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在节点中使用 MongoDb (作为 MongoJS 的一部分)以下是MongoJS的文档

I'm using MongoDb (as part of MongoJS) in Node. Here is the documentation for MongoJS.

I我试图根据条目的 _id 字段在Node内进行调用。当从控制台使用vanilla MongoDB 时,我可以这样做:

I'm trying to do a call within Node based on an entry's _id field. When using vanilla MongoDB from the console, I can do:

db.products。 find({_ id:ObjectId(51d151c6b918a71d170000c7)})

并正确返回我的条目。但是,当我在Node中执行相同的操作时,例如:

and it correctly returns my entry. However, when I do the same thing in Node, like:

db.products.find({"_id": ObjectId("51d151c6b918a71d170000c7")}, function (err, record) {
    // Do stuff
});

我得到 ReferenceError:未定义ObjectId

执行此操作的正确协议是什么?

What is the correct protocol for doing this?

推荐答案

在使用之前需要使用ObjectId函数:

You need to require the ObjectId function before using it:

var ObjectId = require('mongodb').ObjectID;

这篇关于通过Node中的“_id”搜索MongoDB条目的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆