node.js mongodb select document by _id node-mongod

2019-01-13 02:02发布

问题:

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?

回答1:

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


回答2:

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


回答3:

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



回答4:

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


回答5:

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.



回答6:

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

});



回答7:

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

 });`