![](/img/trans.png)
[英]How to update only specific field in object within an array Mongodb
[英]Mongodb update array for specific fields only
我有一个主题的 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 中?
您使用的架构设计得很糟糕。 您在这里可以做的是创建另一个模式TopicQuestionSchema
并为其所属的主题添加一个ref
。
var TopicQuestionSchema = new Schema({
questionTitle: String,
answer: String,
order: Number,
topic: {type: ObjectId, ref: 'Topic'} // the name of your model
}
通过这种方式,您仍然可以跟踪问题所属的主题,并且仍然可以轻松更新订单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.