【发布时间】:2021-11-16 18:44:30
【问题描述】:
编辑: 在尝试了许多不同的方法后,我找到了一个可行的解决方案,可以将任何对象映射到 mongoose 理解的格式。在此处查看解决方案:https://stackoverflow.com/a/69547021/17426304
const updateNestedObjectParser = (nestedUpdateObject) => {
const final = {
}
Object.keys(nestedUpdateObject).forEach(k => {
if (typeof nestedUpdateObject[k] === 'object' && !Array.isArray(nestedUpdateObject[k])) {
const res = updateNestedObjectParser(nestedUpdateObject[k])
Object.keys(res).forEach(a => {
final[`${k}.${a}`] = res[a]
})
}
else
final[k] = nestedUpdateObject[k]
})
return final
}
原始问题:
我有一个猫鼬结构
ChildSchema = {
childProperty: String,
childProperty2: String
}
MainSchema = {
mainProperty: String,
mainProperty2: String,
child: childSchema
}
在我的更新函数中,我想传递mainSchema 的部分对象,并且只更新我传递给函数的属性。
这适用于我的mainSchema 上的直接属性,但不适用于我的childSchema。它用我的请求给出的部分对象覆盖整个子属性。
所以我的更新对象看起来像这样
const updates = {
child: {
childProperty2: 'Example2'
}
}
如何只更新 childProperty2 而不删除 childProperty?
在此示例中,仅更新每个属性很容易,但现实世界的对象要大得多,并且可以嵌套到多个级别。
我尝试使用解构,但它似乎不起作用
const example = MainSchema.findOne({_id})
if (updates.child) example.child = {...example.child, ...updates.child} // Does not work
mongoose (6.0) 中有解决方案吗?
【问题讨论】:
标签: javascript node.js mongodb express mongoose