将新的卡对象推送到对象的嵌套阵列



我的Accounts模型中有这样的结构:

{
cards: {
starter: [],
intermediate: [],
advanced: [ {Object}, {Object}, {Object} ]
},
firstName: 'Sepideh',
email: 'sepideh@example.com',
}

上面的cards.advanced阵列中的Objects类似于:

{
cards: [
{ // this is a single card object 
cardTitle: 'this card is for you',
performance: [],
cardID: 32,
}
],
unit: 3 // this is the unit we want to push our new card object into
}

假设我可以使用给定的电子邮件访问上面的文档(或者换句话说,帐户(:

const account = await db.Account.findOne({ email: 'sepideh@example.com' });

我们如何将一个新的卡对象推送到具有unit: 3(是的,到目前为止这是唯一的单元(属性的嵌套卡数组中,并像这样保存Sepideh帐户:

{
cards: {
starter: [],
intermediate: [],
advanced: [
{
cards: [
{ // this is a single card object 
cardTitle: 'this card is for you',
performance: [],
cardID: 32,
}
{ // this is new pushed card object 
cardTitle: 'this card is for me',
performance: [],
cardID: 33,
}
],
unit: 3 // this is the unit we want to push our new card object into
},
{Object},
{Object}
] // end of advanced array
},
firstName: 'Sepideh',
email: 'sepideh@example.com',
}

我试着用这些家伙选择文件的第三单元,但他们都不起作用:

const userUnit = await account.findOne({'cards.advanced.unit': unit});
const userUnit = await account.findOne({'cards.advanced.unit': unit});
const userUnit = await account.find({}, {'cards.advanced.unit': {$elemMatch: {unit: unit}}}); 
const userUnit = await db.Account.findOne({ email: email, 'cards.advanced.unit': unit});

然后我会将我的新卡对象推送到userUnit并调用await account.save();

唯一有效的是选择这样的纯JavaScript代码:

const userUnit = account.cards.advanced.find(e => e.unit == unit);

这次我无法将更改保存到数据库。。。(我不知道如何保存。(

你会怎么做?

您可以直接将$push运算符与$position运算符一起使用,后者允许您指定应更新的子元素:

await db.Account.update({ email: "sepideh@example.com", "cards.advanced.unit": 3 },
{ $push: { "cards.advanced.$.cards": { cardTitle: 'this card is for me', performance: [], cardID: 33 } } })

如果你想动态评估你的路径,你可以使用计算的属性名称:

let path = "advanced";
await db.Account.update(
{ email: "sepideh@example.com", ["cards." + path + ".unit"]: 3 },            
{ $push: { ["cards." + path + ".$.cards"]: { cardTitle: 'this card is for me', performance: [], cardID: 33 } } })

Mongo游乐场

最新更新