findById是否比findOne({userId:userId})快?

时间:2018-09-04 21:01:32

标签: javascript mongodb mongoose

我的架构设置如下:

employment = new Schema({
  userId: {
    type: Schema.Types.ObjectId,
    ref: "Users"
  }
  ...
})

现在,我正在通过搜索工作集合中的userId来查询用户的工作。将employeeId引用保存在用户模型和findById中会更快吗?还是微不足道?

感谢任何帮助,谢谢

1 个答案:

答案 0 :(得分:0)

从性能的角度来看,重新编写我们拥有的文档是相同的: findById 的定义: /** * Finds a single document by its _id field. `findById(id)` is almost* * equivalent to `findOne({ _id: id })`. If you want to query by a document's * `_id`, use `findById()` instead of `findOne()`. * * The `id` is cast based on the Schema before sending the command. * * This function triggers the following middleware. * * - `findOne()` * * \* Except for how it treats `undefined`. If you use `findOne()`, you'll see * that `findOne(undefined)` and `findOne({ _id: undefined })` are equivalent * to `findOne({})` and return arbitrary documents. However, mongoose * translates `findById(undefined)` into `findOne({ _id: null })`. https://github.com/Automattic/mongoose/blob/master/lib/model.js