【问题标题】:node.js mongodb select document by _id node-mongodb-nativenode.js mongodb 通过_id node-mongodb-native 选择文档
【发布时间】:2011-06-21 14:45:10
【问题描述】:

我正在尝试按 id 选择文档

我试过了:

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

collection.update({ "_id": theidID }

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

也试过了:

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

这给了我一个错误 500...

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

collection.update({ _id: o_id }

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

【问题讨论】:

  • collection.find({"_id": ObjectId(theidID)}) 应该可以工作。
  • @Bugai13 我放弃了,最终为每个文档分配了一个自定义 ID。
  • 我需要这个来进行选择/查找(甚至不是更新)。运气好吗?
  • 如果你没有引用正确的序列化器,它将无法工作。
  • @BernieHackett 此方法不适用于节点运行时 12.13 和 mongodb 版本 3.4。它给出了这里描述的错误stackoverflow.com/questions/26453507/…

标签: javascript mongodb node.js


【解决方案1】:
var mongo = require('mongodb');
var o_id = new mongo.ObjectID(theidID);
collection.update({'_id': o_id});

【讨论】:

  • 2016 年 - 仍然可以正常工作。如果你没有native_parser:false - 请查看下面的 Raphael 回复
  • 这行得通。确保您在 require('mongodb') 上而不是在 require('mongodb').MongoClient 上调用 ObjectID()
  • 这样我得到了mongoClient.ObjectID is not a constructor 错误。
  • 现在ObjectID 已被弃用,应该改用ObjectId
【解决方案2】:

这是对我有用的方法。

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】:

    现在你可以使用这个了:

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

    您可以查看文档here

    【讨论】:

    • 是否可以使用 ES6 风格的import 语句代替require('mongodb').ObjectID
    【解决方案4】:

    native_parser:false:

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

    native_parser:true:

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

    【讨论】:

      【解决方案5】:

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

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

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

      【讨论】:

        【解决方案6】:
        /* get id */
        const id        = request.params.id; // string "5d88733be8e32529c8b21f11"
        
        /* set object id */
        const ObjectId  = require('mongodb').ObjectID;
        
        /* filter */
        collection.update({ 
            "_id": ObjectId(id)
        } )
        

        【讨论】:

          【解决方案7】:

          这对我有用。 使用 mongoDB

          const mongoDB = require('mongodb')

          然后在底部我正在拨打我的特快电话。

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

          【讨论】:

            【解决方案8】:

            答案取决于您作为 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();    
                    } 
                  }
                )  
              } 
            })
            

            });

            【讨论】:

              【解决方案9】:

              ObjectId 报告在“mongodb”中的 find() 函数内调用时已弃用:如果 ObjectId 像这样导入,则为“^4.1.2”

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

              相反,当我使用命名导入导入它时,没有弃用警告

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

              然后我可以定期调用它

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

              【讨论】:

                【解决方案10】:

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

                FindById:

                在 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

                【讨论】:

                  【解决方案11】:

                  我正在使用客户端 "mongodb": "^3.6.2" 和服务器版本 4.4.1

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

                  如果你想复制和粘贴这里就是你所需要的。

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

                  【讨论】:

                    猜你喜欢
                    • 2015-11-08
                    • 2017-05-22
                    • 1970-01-01
                    • 2020-09-18
                    • 2015-05-08
                    • 2020-03-14
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多