0

I am attempting to update (or insert) an attribute of an object within an array in MongoDB, but I don't seem to be able to access the array (apps), or the attribute (appId).

Basically, what's happening is the array of "apps" is being created, but the appId is not populating as it should be.

Can anyone take a look and provide some insight?

Template.CurriculumBuilder.events({
   'submit #addToCurriculum': function(e) {
    event.preventDefault();

    const appId = this._id;
    console.log('Here is the app id --> ' + appId)

    const userId = Meteor.user()._id;
    console.log('Here is the user id --> ' + userId);

    const doc = Curriculum.findOne({ user: userId });
    console.log('Here is the doc id --> ' + doc._id)

    Curriculum.update(doc._id, { $set: { apps: [{ $addToSet: { appId: appId } } ] } } );
    console.log('Apps have been added to --> ' + doc._id)

    return false;
}
});

UPDATE

As answered below, the DB call should be:

Curriculum.update(doc._id,{ $addToSet: { apps: { appId: appId } } } );

1 Answer 1

1

You don't need the $set or the square brackets:

Curriculum.update(doc._id,{ $addToSet: { apps: { appId: appId } } );

In English:

add the object {appId: appId} to the array apps in the document whose _id is doc._id

Sign up to request clarification or add additional context in comments.

4 Comments

Sure. I think I just did. One another quick question. Would inserting data into a new Curriculum work similarly? So, Curriculum.insert({ $addToSet: { apps: { appId: appId } } ); ?
I think you'd want Curriculum.insert({ apps: [{ appId: appId }] } ); to initialize.
What if, I have a separate Array called "userAppList" ... with multiple ID's, already created BEFORE I want to "Insert" or create the document?
Then you can just do: Curriculum.insert({ apps: userAppList } )

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.