【问题标题】:Mongodb update array for specific fields onlyMongodb 仅针对特定字段更新数组
【发布时间】:2020-03-13 08:35:58
【问题描述】:

我有一个主题的 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 更新我的主题问题 order

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

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

如何根据reorderList进行更新,同时保留topicQuestion中的原始数据?

【问题讨论】:

    标签: node.js json mongodb express


    【解决方案1】:

    您使用的架构设计不当。您可以在此处创建另一个架构 TopicQuestionSchema 并将 ref 放入它所属的主题。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-04
      相关资源
      最近更新 更多