在Mongoose中,Model.findOne()和Model.findById()有什么区别?

时间:2021-07-18 13:23:20

Consider we are searching a document from MongoDB based on the _id value. Which one of the following code is efficient ?

考虑我们正在根据_id值从MongoDB中搜索文档。以下哪个代码有效?

  1. ModelObj.findById(IdValue).exec(callback);

    ModelObj.findById(IdValue).exec(回调);

  2. ModelObj.findOne({ '_id': IdValue}).exec(callback);

    ModelObj.findOne({'_ id':IdValue})。exec(callback);

I feel ModelObj.findById() is efficient, but what are the supportive reasons or How is it efficient?

我觉得ModelObj.findById()是有效的,但有什么支持的原因或它是如何有效的?

3 个解决方案

#1


35  

findById is just a convenience function that does exactly the same thing as the findOne call you show.

findById只是一个便利函数,与你显示的findOne调用完全相同。

Here's the source:

这是来源:

Model.findById = function findById (id, fields, options, callback) {
  return this.findOne({ _id: id }, fields, options, callback);
};

#2


0  

findById(id) is just syntactic sugar of the find({_id : id}) or findOne({_id: id})

findById(id)只是find({_ id:id})或findOne({_ id:id})的语法糖

#3


-2  

Using .findOne makes the database look through its records checking each bson document to find the relevant variable and then check the value, if mongo knows its looking for the internally indexed _id field it doesn't have to look through each document

使用.findOne使数据库查看其记录,检查每个bson文档以查找相关变量,然后检查值,如果mongo知道它正在查找内部索引的_id字段,则不必查看每个文档

#1


35  

findById is just a convenience function that does exactly the same thing as the findOne call you show.

findById只是一个便利函数,与你显示的findOne调用完全相同。

Here's the source:

这是来源:

Model.findById = function findById (id, fields, options, callback) {
  return this.findOne({ _id: id }, fields, options, callback);
};

#2


0  

findById(id) is just syntactic sugar of the find({_id : id}) or findOne({_id: id})

findById(id)只是find({_ id:id})或findOne({_ id:id})的语法糖

#3


-2  

Using .findOne makes the database look through its records checking each bson document to find the relevant variable and then check the value, if mongo knows its looking for the internally indexed _id field it doesn't have to look through each document

使用.findOne使数据库查看其记录,检查每个bson文档以查找相关变量,然后检查值,如果mongo知道它正在查找内部索引的_id字段,则不必查看每个文档