首页 > 解决方案 > Mongodb 仅针对特定字段更新数组

问题描述

我有一个主题的 json 数组reorderList

const reorderList = [
    { _id: '5e6b419c76a16d5c44d87132', order: 0 },
    { _id: '5e6b41a276a16d5c44d87139', order: 1 },
    { _id: '5e6b41a776a16d5c44d87140', order: 2 }
]

而我的 TopicSchema 是这样的:

var TopicSchema = new Schema({
    topicTitle: String,
    topicQuestion: [
        {           
            questionTitle: String,
            answer: String,
            order: Number
        }
    ]
}

现在我想根据 reorderList 的_id更新我的主题问题顺序

但是下面的语句将替换 topicQuestion 中的所有内容(例如 questionTitle 和 answer 将被删除)

Topic.findOneAndUpdate(
    { '_id': topicId },
    { $set: { 'topicQuestion': reorderList } }, //replaces here
    { upsert: true },
    function (err, response) {
         ...
    });

如何根据 reorderList 更新它并将原始数据保留在 topicQuestion 中?

标签: node.jsjsonmongodbexpress

解决方案


您使用的架构设计不当。您可以在这里做的是创建另一个模式,TopicQuestionSchema并将 a 放入ref它所属的主题。

var TopicQuestionSchema = new Schema({          
    questionTitle: String,
    answer: String,
    order: Number,
    topic: {type: ObjectId, ref: 'Topic'} // the name of your model
}

这样,您仍然可以跟踪问题所属的主题,并且仍然可以轻松更新顺序。


推荐阅读