将新的卡片对象推送到嵌套的对象数组

时间:2021-07-16 13:51:22

标签: javascript node.js mongodb mongoose

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

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

上面Objects数组中的cards.advanced如下:

{
  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',
}

我尝试使用这些人选择文档的第 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);

这次我无法保存对数据库的更改...(我不知道如何保存它...)

你会怎么做?

1 个答案:

答案 0 :(得分:2)

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

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 } } })

如果您希望动态评估您的路径,您可以使用 computed property names:

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 Playground

相关问题