Javascript node.js mongodb 通过 _id 选择文档 node-mongodb-native

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4902569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:40:34  来源:igfitidea点击:

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

javascriptmongodbnode.js

提问by Mark

I'm trying to select a document by id

我正在尝试通过 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...

这给了我一个错误 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?

这些都不起作用。如何通过_id选择?

回答by KingPin

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

回答by ncoronges

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

回答by nktssh

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

您可以在此处查看文档

回答by Raphael Schweikert

With native_parser:false:

native_parser:false

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

With native_parser:true:

native_parser:true

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

回答by Yarik

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

我刚刚在控制器文件中的 Node.js 应用程序中使用了这段代码,它可以工作:

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.

之前不要忘记安装“mongodb”,如果您使用带有“presave”的bcrypt加密密码,请确保在每次修改DB中的记录后都不会加密密码。

回答by antelove

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

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

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

回答by Roger Perez

This is what worked for me. Using mongoDB

这对我有用。使用 mongoDB

const mongoDB = require('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));

 });`

回答by jmontross

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.

答案取决于您作为 id 传入的变量类型。我通过执行查询并将我的 account_id 存储为 ._id 属性来提取对象 ID。使用此方法,您只需使用 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();    
        } 
      }
    )  
  } 
})

});

});

回答by Diego Mauricio Guerrero

If you use Mongosee, you can simplify the function

如果使用Mongosee,可以简化功能

FindById:

FindById:

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

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

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