node.js - 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 中?
解决方案
您使用的架构设计不当。您可以在这里做的是创建另一个模式,TopicQuestionSchema
并将 a 放入ref
它所属的主题。
var TopicQuestionSchema = new Schema({
questionTitle: String,
answer: String,
order: Number,
topic: {type: ObjectId, ref: 'Topic'} // the name of your model
}
这样,您仍然可以跟踪问题所属的主题,并且仍然可以轻松更新顺序。
推荐阅读
- python-3.x - 我使用 pip 安装 pyautogui,但它仍然指向我“没有名为 pyautogui 的模块”
- java - Java同步方法调用但FIFO
- javascript - 从 Typescript 中的重复值创建键数组
- scala - 由于 sbt-rpm.repo 导致 linux 补丁失败
- r - 过滤器之间的双向反应性
- javascript - 如何修复未捕获的类型错误:无法读取 null 的属性“值”
- docusignapi - Cosign 数字签名设备 SAPI 本地
- python - 退避以仅重试失败的 API 调用,而不是使用 asyncio 重试所有 API 调用
- regex - Notepad++ 中的正则表达式获取资源键
- javascript - 使用 Ant Design UI 库禁用标签