使用node.js mongodb原生驱动程序按_id选择文档

115

我正在尝试通过 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进行选择?


4
collection.find({"_id": ObjectId(theidID)}) 应该可以运行。 - Bernie Hackett
@Bugai13 我放弃了,最终为每个文档分配了一个自定义ID。 - Mark
我需要用于选择/查找(而不是更新)。有运气吗? - strager
如果您没有正确序列化程序的引用,它将无法正常工作。 - MK_Dev
@BernieHackett 这种方法不适用于使用Node运行时12.13和MongoDB版本3.4的情况。它会出现在这里描述的错误 https://dev59.com/Pl8d5IYBdhLWcg3wxklq - Kusal Hettiarachchi
@Bernie Hackett。10年过去了。仍然拯救着某些人的屁股!感谢并点赞评论。 - projektorius96
12个回答

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

1
2016年 - 仍然正常工作。 如果没有,也许你有native_parser:false - 请查看Raphael的回复。 - fider
2
这个是行得通的。确保你在 require('mongodb') 上调用了 ObjectID(),而不是在 require('mongodb').MongoClient 上调用。 - Alec O
通过这种方式,我得到了“mongoClient.ObjectID不是构造函数”的错误。 - Sachin Shah
4
现在 ObjectID 已经被弃用,应该使用 ObjectId 替代。 - YakovL

81

这是对我有效的方法。

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

25

现在你可以直接使用这个:

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

您可以在此处查看文档。


可以使用ES6风格的import语句代替require('mongodb').ObjectID吗? - user1063287

12

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

10

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

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

在使用bcrypt的"presave"加密密码保存之前,不要忘记先安装"mongodb",并确保在数据库中记录修改后不会重新加密密码。


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: 新的对象ID


4

如果像这样导入ObjectId,"mongodb": "^4.1.2"中的find()函数内调用它会报废:

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

相反,当我使用具名导入方式导入时,就没有弃用警告了

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

那么我就可以定期调用它

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

2

以下是我使用MongoDB的解决方案:

const mongoDB = require('mongodb')

然后,在我的Express get调用底部进行操作。

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

 });`

1
答案取决于您传递的变量类型作为ID。 我通过查询并将我的账户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();    
        } 
      }
    )  
  } 
})

});


0
在Mongoose中,Model.findById()函数用于通过_id查找一个文档。 findById()函数接受单个参数,即文档ID。如果MongoDB找到具有给定id的文档,则它返回解析为Mongoose文档的Promise,否则返回null
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);

当您调用findById(_id)时,Mongoose在幕后调用findOne({ _id })。这意味着findById()会触发findOne()中间件
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将查询转换为与您的模式匹配。 这意味着如果您的_idMongoDB ObjectId,则可以将_id作为字符串传递,Mongoose会将其转换为ObjectId。

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

源代码


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接