I have this structure in my Accounts Model:
{
cards: {
starter: [],
intermediate: [],
advanced: [ {Object}, {Object}, {Object} ]
},
firstName: 'Sepideh',
email: 'sepideh@example.com',
}
The Objects inside cards.advanced array above are like:
{
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
}
Assuming I can access the document above (or account in other words) with the given email:
const account = await db.Account.findOne({ email: 'sepideh@example.com' });
How can we push a new card object into the nested cards array with unit: 3 (yes so far this is the only unit) property and save Sepideh account like this:
{
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',
}
I have tried to select the unit 3 of the document using these guys and none of them worked:
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});
Then I would push my new card object to the userUnit and call await account.save();
The only thing which is working is pure JavaScript code like this to select:
const userUnit = account.cards.advanced.find(e => e.unit == unit);
This time I cannot save the changes to the database... (I don't know how to save it..)
How would you do this?
You can use the $push operator directly along with the $ positional operator which allows you to specify which sub-element should be updated:
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 } } })
If you want your path to be evaluated dynamically you can use 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 } } })