2016-12-02 71 views
1

如何覆蓋基於給定數組作爲源的文檔的數組屬性?Mongoose:覆蓋更新的數組屬性

模式:

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的數組,我想覆蓋的標籤屬性。我現在遇到的問題是它添加了新的標籤,但它不會刪除不在源數組中的標籤。

我目前正在使用findOneAndUpdate如下更新:

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

回答

1

你嘗試$集合運算符?

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

+0

謝謝,$ set操作符做到了。無法在最新的貓鼬文檔中找到它。 – scripton

+0

$設置運營商是好的 –