【问题标题】:Mongoose.js schema options for embedded documents are not working嵌入式文档的 Mongoose.js 架构选项不起作用
【发布时间】:2014-07-10 22:30:39
【问题描述】:

我对 node.js 和猫鼬很陌生。我的架构如下。

var sub = Schema({"title": {type: String, required: true, trim: true, unique: true},
                  "uniqueId": Schema.ObjectId}

var main = Schema({"name": {type: String, required: true, index: { unique: true, dropDups: true},
                  "subs": [sub]}

这是有效的。文档被插入。正在添加潜艇。问题如下。

我在这里期待的是当我将新的 sub 添加到 main 中时。它将检查标题是否存在,如果不存在则抛出异常。它将检查标题是否唯一。此外,它会自行将对象 ID 分配给 uniqueId 字段。但这并没有发生。它不检查标题是否存在且唯一。此外,objectId 没有分配给 uniqueId,而是分配给 _id。

这是将 sub 添加到 main 中的代码。

MainModel.findByIdAndUpdate(
        request["_id"], 
        {$push: {subs: {"title": "New title"}}}, {}, function(err, doc) {
            console.log(err);
            console.log(doc);
        }
    );

Mongoose 将此查询记录为。

MainModel.findAndModify({ _id: ObjectId("537caa880519db710d7b5b2a") }) [] { '$push': { subs: { _id: ObjectId("537d6b96f927d6573c6e1044"),  title: 'New title' } } } { upsert: false, new: true }

如果您看到 ObjectId 被分配给 _id 而不是 uniqueId。此外,它不检查标题是否存在并且是唯一的。

可能是我这边犯了愚蠢的错误。我在这里错过了什么。

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    使用任何 findAndModify 助手时,不会应用默认值、设置器、验证器和中间件。看这里http://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate

    【讨论】:

    • 感谢您指出这一点。那么,唯一的解决方案是查找、更改文档并保存文档吗?有没有更好的解决方案?因为,我必须先检索,然后遍历数组,更改数组元素,然后更新文档。
    • 视情况而定,有时最好(从性能的角度来看 fx)确保代码的一致性
    猜你喜欢
    • 1970-01-01
    • 2016-06-07
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多