【问题标题】:Using mongoose findById() over more than one field?在多个字段上使用猫鼬 findById()?
【发布时间】:2016-07-21 12:53:55
【问题描述】:

我有一个看起来像这样的模型

var mongoose = require('mongoose');
var tableSchema = new mongoose.Schema({
    version: { type: String, uppercase: true , required: true, trim: true },
    name: { type: String, uppercase: true , required: true, trim: true },
    descr: String
});
uctableSchema.index({ version: 1, name: 1 }, { unique: true }); 
module.exports = mongoose.model('Table', tableSchema); 

这个模型会生成一个这样的集合

> db.tables.findOne()
{
        "_id" : ObjectId("56fc97d6e81ed6faf5e75b58"),
        "version" : "4",
        "name" : "address",
        "descr" : "contact address table"
}

没关系。我故意让猫鼬生成自动_id。

我创建了一个唯一的复合索引作为主键。

数据实际上是通过 json 文件从 RDBMS 导入的。所以 mongoimport 会为它自动生成 _id。这很好。

_id 值没有实际意义,我想通过复合主键检索、修改和删除数据。

就我而言,我还能使用 findById 吗?

Model.findById(id, [projection], [options], [callback])
Model.findByIdAndUpdate(id, [update], [options], [callback])   
Model.findByIdAndRemove(id, [options], [callback])

我了解第一个参数 id 指的是我不想使用的 _id。

有没有办法让 id 参数引用我的复合键、版本和名称?或者我根本不应该使用 findById?

谢谢,

【问题讨论】:

    标签: mongoose


    【解决方案1】:

    不,xxxById 方法都设计为仅与 _id 一起使用。

    例如,这里是findById的来源:

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

    您需要使用更通用的findOnefindOneAndUpdatefindOneAndRemove 方法。

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 1970-01-01
      • 2019-02-08
      • 1970-01-01
      • 2020-02-17
      • 2016-09-19
      • 2019-02-15
      相关资源
      最近更新 更多