什么时候在猫鼬中对ObjectId(“ string-id”)使用新的ObjectId(“ string-id”)?

时间:2018-12-27 09:20:15

标签: javascript node.js mongodb mongoose objectid

因为我想与我的代码(Node.js)保持一致

当我有一个查询并且需要使用id值(这是一个唯一的对象)搜索某些内容时,执行该查询的最佳方法是什么?

User.findOne({id: new ObjectId("82jf20k2k...")}...

OR

User.findOne({id: ObjectId("82jf20k2k...")}...

每次创建新实例并用对象填充内存似乎是错误的。

使用 new ObjectId 的唯一合理时间是在为所有其他操作插入数据时,我会使用 ObjectId

4 个答案:

答案 0 :(得分:2)

检查source code

$(document).ready(function(){

         $("a.button").addClass('btn disabled');
          $("a.remove").addClass('ui-state-disabled'); // this is my datatable remove button with class remove
         $("a.button").css("margin-top", "-5px"); 
         $("a.button").css("pointer-events", "none");
   $('[type=file]').attr('disabled', 'disabled');
})

对于我来说,做/** * Create a new ObjectID instance * * @class * @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. * @property {number} generationTime The generation time of this ObjectId instance * @return {ObjectID} instance of ObjectID. */ var ObjectID = function ObjectID(id) { // Duck-typing to support ObjectId from different npm packages if (id instanceof ObjectID) return id; if (!(this instanceof ObjectID)) return new ObjectID(id); this._bsontype = 'ObjectID'; // more code new是一样的事情,好像它不是ObjectId("82jf20k2k...")的实例一样,它将创建一个新实例并返回它。

答案 1 :(得分:0)

您应该使用第二个选项,即

  

User.findOne({id:ObjectId(“ 82jf20k2k ...”)} ...

您是对的第一个是在内存中创建不必要的对象。如果要在运行时生成ObjectID,应使用 New 关键字。

答案 2 :(得分:0)

您可以像这样使用它:

User.findOne({ id: "82jf20k2k..." })

不需要“ ObjectId()”,因为findOne会尝试将字符串转换为ObjectId。

此外,如果要按ID搜索文档,请使用findById,因为它更受欢迎。

参考: mongoose model.js from Github

答案 3 :(得分:0)

我建议您使用Model.findById()而不是Model.findOne(_id:id)来基于_id查找文档。

您还可以在Mongoose Documentation上找到更多信息。

相关问题