node.js mongodb select document by _id node-mongodb-native

JavascriptMongodbnode.js

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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.

Solution 6 - Javascript

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

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

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

Solution 7 - Javascript

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

 });`

Solution 8 - Javascript

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

Solution 9 - Javascript

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

});

Solution 10 - Javascript

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

Solution 11 - Javascript

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

Solution 12 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarkView Question on Stackoverflow
Solution 1 - JavascriptKingPinView Answer on Stackoverflow
Solution 2 - JavascriptncorongesView Answer on Stackoverflow
Solution 3 - JavascriptnktsshView Answer on Stackoverflow
Solution 4 - JavascriptRaphael SchweikertView Answer on Stackoverflow
Solution 5 - JavascriptYarikView Answer on Stackoverflow
Solution 6 - JavascriptanteloveView Answer on Stackoverflow
Solution 7 - JavascriptRoger PerezView Answer on Stackoverflow
Solution 8 - JavascriptemirView Answer on Stackoverflow
Solution 9 - JavascriptjmontrossView Answer on Stackoverflow
Solution 10 - JavascriptDiego Mauricio GuerreroView Answer on Stackoverflow
Solution 11 - JavascriptCollin ThomasView Answer on Stackoverflow
Solution 12 - JavascriptMansour AshrafView Answer on Stackoverflow