简体   繁体   English

Mongodb 仅针对特定字段更新数组

[英]Mongodb update array for specific fields only

I have a json array reorderList for a topic:我有一个主题的 json 数组reorderList

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

And my TopicSchema is like this:而我的 TopicSchema 是这样的:

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

Now I want to update my topic questions order based on the reorderList's _id .现在我想根据 reorderList 的_id更新我的主题问题顺序

But the below statement will replace all the things from topicQuestion (eg questionTitle and answer will be removed)但是下面的语句将替换 topicQuestion 中的所有内容(例如 questionTitle 和 answer 将被删除)

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

How to update it based on reorderList and also keep the original data inside topicQuestion?如何根据 reorderList 更新它并将原始数据保留在 topicQuestion 中?

The schema that you're using is badly designed.您使用的架构设计得很糟糕。 What you can do here is create another schema, TopicQuestionSchema and put a ref to the topic it belongs to.您在这里可以做的是创建另一个模式TopicQuestionSchema并为其所属的主题添加一个ref

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

This way you can still keep track of the topic the questions belong to, and still be able to update the order easily.通过这种方式,您仍然可以跟踪问题所属的主题,并且仍然可以轻松更新订单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM