118

I'm trying to select a document by id

I've tried:

collection.update({ "_id": { "$oid": + theidID } }

collection.update({ "_id": theidID }

collection.update({ "_id.$oid": theidID }}

Also tried:

collection.update({ _id: new ObjectID(theidID ) }

This gives me an error 500...

var mongo = require('mongodb')
var BSON = mongo.BSONPure;
var o_id = new BSON.ObjectID(theidID );

collection.update({ _id: o_id }

None of these work. How to select by _id?

6
  • 4
    collection.find({"_id": ObjectId(theidID)}) should work. Commented Feb 4, 2011 at 21:48
  • @Bugai13 I gave up and ended up assigning a custom ID for every doc. Commented Feb 27, 2011 at 17:27
  • I need this for a select/find (not an update, even). Any luck? Commented May 25, 2011 at 12:49
  • It won't work if you don't have a reference to the right serializer. Commented Jun 1, 2012 at 1:48
  • @BernieHackett this method does not work for node runtime 12.13 with mongodb version 3.4. It gives the error described here stackoverflow.com/questions/26453507/… Commented Dec 8, 2019 at 16:41

12 Answers 12

179
var mongo = require('mongodb');
var o_id = new mongo.ObjectID(theidID);
collection.update({'_id': o_id});
Sign up to request clarification or add additional context in comments.

4 Comments

Year 2016 - still works ok. If no maby you had native_parser:false - check Raphael reply below
This works. Make sure the you are calling ObjectID() on require('mongodb') and not on require('mongodb').MongoClient
By this way I got mongoClient.ObjectID is not a constructor error.
Now ObjectID is deprecated, one should use ObjectId instead
81

This the approach that worked for me.

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

var get_by_id = function(id, callback) {
  console.log("find by: "+ id);
  get_collection(function(collection) {
    collection.findOne({"_id": new ObjectId(id)}, function(err, doc) {
       callback(doc);
    });
  });
}

Comments

26

now you can just use this:

var ObjectID = require('mongodb').ObjectID;
var o_id = new ObjectID("yourObjectIdString");
....
collection.update({'_id': o_id});

You can see documentation here

1 Comment

is it possible to use ES6 style import statement instead of require('mongodb').ObjectID?
12

With native_parser:false:

var BSON = require('mongodb').BSONPure;
var o_id = BSON.ObjectID.createFromHexString(theidID);

With native_parser:true:

var BSON = require('mongodb').BSONNative;
var o_id = BSON.ObjectID.createFromHexString(theidID);

Comments

10

I just used this code in Node.js app in controller file, and it works:

var ObjectId = require('mongodb').ObjectId;
...
User.findOne({_id:ObjectId("5abf2eaa1068113f1e")})
.exec(function(err,data){
   // do stuff
})

do not forget to install "mongodb" before, and if you are using encryption of your passwords with bcrypt with "presave", be sure that you will not encrypt password after each modification of the record in DB.

Comments

9

mongodb 4.0.0

/* get id */
const id        = request.params.id; // string "5d88733be8e32529c8b21f11"

/* set object id */
const ObjectId  = require('mongodb').ObjectID;

/* filter */
collection.update({ 
    "_id": ObjectId(id)
} )

mongodb 5.0.0

"_id": new ObjectId(id)

stackoverflow.com: new ObjectId

Comments

4

ObjectId reports deprecated when called inside find() function in "mongodb": "^4.1.2" if the ObjectId is imported like this

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

instead, when I import it with named import there is no deprecated warning

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

then I can call it regularly

const findResult = await collection.find({_id: ObjectId(id)}).toArray();

Comments

2

This is what worked for me. Using mongoDB

const mongoDB = require('mongodb')

Then at the bottom where I am making my express get call.

router.get('/users/:id', (req, res) => {
const id = req.params.id;
var o_id = new mongoDB.ObjectID(id);

const usersCollection = database.collection('users');

usersCollection.findOne({
  _id: o_id
})

.then(userFound => {
  if (!userFound){
    return res.status(404).end();
  }
  // console.log(json(userFound));
  return res.status(200).json(userFound)
})
.catch(err => console.log(err));

 });`

Comments

1

The answer depends upon the variable type you are passing in as the id. I pulled an object id by doing a query and storing my account_id as the ._id attribute. Using this method you simply query using the mongo id.

// begin account-manager.js
var MongoDB   = require('mongodb').Db;
var dbPort      = 27017;
var dbHost      = '127.0.0.1';
var dbName      = 'sample_db';
db = new MongoDB(dbName, new Server(dbHost, dbPort, {auto_reconnect: true}), {w: 1});
var accounts = db.collection('accounts');

exports.getAccountById = function(id, callback)
{ 
  accounts.findOne({_id: id},
    function(e, res) {  
    if (e) {
        callback(e)
    }
    else {
        callback(null, res)
    }

  });
}
// end account-manager.js

// my test file
var AM = require('../app/server/modules/account-manager');

it("should find an account by id", function(done) {

AM.getAllRecords(function(error, allRecords){
  console.log(error,'error')
  if(error === null) {
    console.log(allRecords[0]._id)
    // console.log('error is null',"record one id", allRecords[0]._id)
    AM.getAccountById(          
      allRecords[0]._id,
      function(e,response){
        console.log(response,"response")
        if(response) {
          console.log("testing " + allRecords[0].name + " is equal to " + response.name)
          expect(response.name).toEqual(allRecords[0].name);
          done();    
        } 
      }
    )  
  } 
})

});

Comments

0

If you use Mongosee, you can simplify the function

FindById:

this replace in mongodb: "_id" : ObjectId("xyadsdd434434343"),

example:

// find adventure by id and execute
Adventure.findById('xyadsdd434434343', function (err, adventure) {});

https://mongoosejs.com/docs/api.html#model_Model.findById

Comments

0

I'm using client "mongodb": "^3.6.2" and server version 4.4.1

// where 1 is your document id
const document = await db.collection(collection).findOne({ _id: '1' })
console.log(document)

If you want to copy and paste here's all you need.

const { MongoClient } = require('mongodb')
const uri = '...'
const mongoDb = '...'
const options = {}
;(async () => {
  const client = new MongoClient(uri, options)
  await client.connect()
  const db = client.db(mongoDb)
  const document = await db.collection(collection).findOne({ _id: '1' })
  console.log(document)
)}()

Comments

0

In Mongoose, the Model.findById() function is used to find one document by its _id. The findById() function takes in a single parameter, the document id. It returns a promise that resolves to the Mongoose document if MongoDB found a document with the given id, or null if no document was found.

const schema = new mongoose.Schema({ _id: Number }, { versionKey: false });
const Model = mongoose.model('MyModel', schema);

await Model.create({ _id: 1 });

// `{ _id: 1 }`
await Model.findById(1);

// `null` because no document was found
await Model.findById(2);

When you call findById(_id), Mongoose calls findOne({ _id }) under the hood. That means findById() triggers findOne() middleware.

const schema = new mongoose.Schema({ _id: Number }, { versionKey: false });
schema.pre('findOne', function() {
  console.log('Called `findOne()`');
});
const Model = mongoose.model('MyModel', schema);
await Model.create({ _id: 1 });

// Prints "Called `findOne()`" because `findById()` calls `findOne()`
await Model.findById(1);

Mongoose casts queries to match your schema. That means if your _id is a MongoDB ObjectId, you can pass the _id as a string and Mongoose will convert it to an ObjectId for you.

const _id = '5d273f9ed58f5e7093b549b0';
const schema = new mongoose.Schema({ _id: mongoose.ObjectId }, { versionKey: false });
const Model = mongoose.model('MyModel', schema);

await Model.create({ _id: new mongoose.Types.ObjectId(_id) });

typeof _id; // 'string'
// `{ _id: '5d273f9ed58f5e7093b549b0' }`
const doc = await Model.findById(_id);

typeof doc._id; // 'object'
doc._id instanceof mongoose.Types.ObjectId; // true

Source

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.