【发布时间】:2021-10-16 17:17:40
【问题描述】:
我在 moongose 中有一个模型架构:
const usersSchema = new Schema({
users: [
{
username: { type: String, required: true },
actions: [
{
action: { type: String },
description: { type: String, required: true }
}
]
}
]
});
我的 mongodb 中还有一个文档:
{ user: 'John', action: [{ action: 'Like', description: 'Like post' },{ action: 'Share', description: 'Share post' }] }
现在通过 PATCH 请求,我得到一个更新的对象,我想与旧文档合并
{
users: [
{
user: 'John',
action: [{ action: 'Delete', description: 'Delete Post' }]
},
{
user: 'Robert',
action: [{ action: 'Share', description: 'Share post' }]
}
]
};
我可以从数据库中提取旧文档并使用扩展运算符或Object.assign() 合并对象,但这是有问题的,因为随着时间的推移文档会增加并且拉取操作会花费更长的时间。
这是我尝试得到的最终结果。
{
users: [
{
user: 'John',
action: [
{ action: 'Like', description: 'Like post' },
{ action: 'Share', description: 'Share post' },
{ action: 'Delete', description: 'Delete Post' }
]
},
{
user: 'Robert',
action: [{ action: 'Share', description: 'Share post' }]
}
]
}
【问题讨论】: