【问题标题】:Mongoose: Overwriting array property on updateMongoose:更新时覆盖数组属性
【发布时间】:2017-04-16 20:35:57
【问题描述】:

如何以给定数组为源覆盖文档的数组属性?

架构:

var postSchema = new mongoose.Schema({
    title: { type: String, required: true, index: { unique: true } },
    content: { type: String },
    tags: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Tag' }]
});

我现在有一个包含标签对象 id 的数组,我想覆盖 tags 属性。我现在遇到的问题是它添加了新标签,但它不会删除不在源数组中的标签。

我目前正在使用 findOneAndUpdate 执行更新,如下所示:

// Pseudo code example
Post.findOneAndUpdate({ _id: id }, { tags: ["id1...", "id2..."], {}, cb);

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema mongoose-populate


    【解决方案1】:

    您尝试过 $set 运算符吗?

    Post.findOneAndUpdate({ _id: id }, { $set: {tags: ["id1...", "id2..."]}, {}, cb);

    【讨论】:

    • 谢谢,$set 操作符成功了。在最新的 mongoose 文档中找不到这个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    相关资源
    最近更新 更多