Correct way to search for MongoDB entries by '

2019-01-23 22:59发布

问题:

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

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")})

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
});

I get ReferenceError: ObjectId is not defined.

What is the correct protocol for doing this?

回答1:

You need to require the ObjectId function before using it:

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


回答2:

If you are using MongoJS, you can do:

var ObjectId = mongojs.ObjectId;

Then,

db.users.find({"_id": ObjectId(id)}, function(err, user){...}


回答3:

if you are using mongoose you can try this:

var mongoose = require('mongoose')
usersSchema = mongoose.model('users'),
mongoose.Types.ObjectId("<object_id>")

usersSchema.find({"_id": mongoose.Types.ObjectId("<object_id>")}, function (err, record) {
// Do stuff
});


回答4:

You can also destructure your ObjectId and MongoClient to optimize your code and make it more readable.

const { MongoClient, ObjectId } = require('mongodb');