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

Amo*_*rni 23 mongoose mongodb node.js objectid

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

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

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

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

Joh*_*yHK 42

findById只是一个便利功能,它与findOne您显示的呼叫完全相同.

这是来源:

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


Ron*_*eva 14

findById(id)几乎相当于findOne({ _id: id }).
如果要通过文档的 _id 进行查询,请使用findById()代替findOne()

两个函数都触发findOne(),唯一的区别是它们的处理方式undefined
如果您使用findOne(),您将看到它findOne(undefined)findOne({ _id: undefined })等效于findOne({})并返回任意文档。
但是,猫鼬转换findById(undefined)findOne({ _id: null }).

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

这是来源

Model.findById = function findById(id, projection, options, callback) {
  if (typeof id === 'undefined') {
    id = null;
  }

  if (callback) {
    callback = this.$wrapCallback(callback);
  }

  return this.findOne({_id: id}, projection, options, callback);
};
Run Code Online (Sandbox Code Playgroud)