47

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?

JVG
  • 20,198
  • 47
  • 132
  • 210

5 Answers5

124

You need to require the ObjectId function before using it:

var ObjectId = require('mongodb').ObjectID;
Chris
  • 4,204
  • 1
  • 25
  • 30
  • 4
    I used `var ObjectId = require("mongojs").ObjectId;`, but works just as well! Cheers. – JVG Jul 09 '13 at 10:16
  • 8
    Or [`require('mongoose').Schema.ObjectId`](http://stackoverflow.com/questions/8111846/how-to-set-objectid-as-a-data-type-in-mongoose) – laggingreflex Mar 06 '14 at 00:17
  • 1
    The Mongoose schema one didn't work for me. Mongodb did. – PanMan Jun 09 '16 at 10:57
  • As per `Mongoose`, _To create a new ObjectId please try `Mongoose.Types.ObjectId` instead of using `Mongoose.Schema.ObjectId`. Set the `suppressWarning` option if you're trying to create a hex char path in your schema._ – Vaishak Sep 25 '18 at 06:52
2

If you are using MongoJS, you can do:

var ObjectId = mongojs.ObjectId;

Then,

db.users.find({"_id": ObjectId(id)}, function(err, user){...}
Nidhin David
  • 2,426
  • 3
  • 31
  • 45
Amol
  • 21
  • 2
2

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
});
ofir_aghai
  • 3,017
  • 1
  • 37
  • 43
2

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

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

Here's another way to utilise objectId when using mongoose.

// at the top of the file
const Mongoose = require('mongoose')
const ObjectId = Mongoose.Types.ObjectId;

// when using mongo to collect data
Mongoose.model('users', userSchema).findOne({ _id: 
    ObjectId('xyz') }, function (err, user) {
        console.log(user)
        return handle(req, res)
    })
})
Nick Taras
  • 696
  • 8
  • 15