[英]pushing a new card object to the nested array of objects
我的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
(是的,目前是唯一的 unit)属性的嵌套卡片数组中,并像这样保存 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',
}
我尝试使用这些人选择文档的第 3 单元,但没有一个工作:
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运算符与$ 位置运算符一起使用,后者允许您指定应更新哪个子元素:
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 } } })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.