Mongodb 如何在Mongoose中合并两个对象

Mongodb 如何在Mongoose中合并两个对象,mongodb,mongoose,Mongodb,Mongoose,我想知道如何使用mongoose合并对象 例如,假设我的文档是: { a: { x: 2, y: 3 } } 我有一个目标: { x: 3, z: 5 } 我希望合并它们,以便我现在有: { a: { x: 3, y: 3, z: 5 } } 您可以尝试以下方法: Object.assign(doc1.a, doc2.toObject()) doc1.save()

我想知道如何使用mongoose合并对象

例如,假设我的文档是:

{
    a: {
        x: 2,
        y: 3
    }
}
我有一个目标:

{
    x: 3,
    z: 5
}
我希望合并它们,以便我现在有:

{
    a: {
        x: 3,
        y: 3,
        z: 5
    }
}

您可以尝试以下方法:

Object.assign(doc1.a, doc2.toObject())
doc1.save()
 const user = await User.findById(12345); // your Mongoose model
 const existingProperties = user.properties.toObject(); // existing properties from the user
 const providedProperties = { a: 1 }; // new properties to be inserted/overwritten

 // merge the two objects, this will overwrite properties in existingProperties if
 // they are provided in the providedProperties object, otherwise they will be attached
 const mergedProperties = { ...existingProperties, ...providedProperties };

 user.set({ properties: mergedProperties });
 const updatedUser = await user.save();
但您可能希望在合并文档之前使用
删除doc2.\u id

您可以使用:

assign()方法用于复制所有 从一个或多个源对象到目标对象的可枚举自身属性 对象它将返回目标对象

例如:

const object1 = {
  a: 1,
  b: 2,
  c: 3
};

const object2 = Object.assign({c: 4, d: 5}, object1);
console.log(object2.c, object2.d);
或者,您也可以使用:


关于
Object.assign()
的其他答案对我不起作用,但您可以使用
spread
操作符,如下所示:

Object.assign(doc1.a, doc2.toObject())
doc1.save()
 const user = await User.findById(12345); // your Mongoose model
 const existingProperties = user.properties.toObject(); // existing properties from the user
 const providedProperties = { a: 1 }; // new properties to be inserted/overwritten

 // merge the two objects, this will overwrite properties in existingProperties if
 // they are provided in the providedProperties object, otherwise they will be attached
 const mergedProperties = { ...existingProperties, ...providedProperties };

 user.set({ properties: mergedProperties });
 const updatedUser = await user.save();