简体   繁体   中英

How to Update An Array of Subdocuments on a MongoDB Collection in MeteorJS

I'm having a problem updating a mongo collection in Meteor.

Perhaps I just don't understand how $addtoset works.

Here is my basic document, more or less this is in my fixtures.js where I initialize my project:

var someUser = Meteor.users.findOne("W9YEs84QFhZzJeB6j");

var NewIdea = Ideas.insert({
  title: "This Is a Title",
  body: "Blah Blah Blah Body Goes Here",
  userId: someUser._id,
  author: someUser.profile.name,
  timestamp: new Date(now - 5 * 3600 * 1000),
  score: [],
  overallScore: 0,
  votedOnBy: [],
  timesVotedOn: 0
});

Here is what I want it to look like after the update:

{
  _id: "bKXXrpYmppFBfq9Kx",
  title: "This Is a Title",
  body: "Blah Blah Blah Body Goes Here",
  userId: "W9YEs84QFhZzJeB6j",
  author: "Users Name",
  timestamp: ISODate("2016-06-07T20:37:05.775Z"),
  score: [
    {
      userId: ""W9YEs84QFhZzJeB6j",
      score: 1
    }
  ],
  overallScore: 1,
  votedOnBy: [
    "W9YEs84QFhZzJeB6j"
  ],
  timesVotedOn: 1
}

Here is the code I'm using to update (which is not working):

Ideas.update("bKXXrpYmppFBfq9Kx", {
  $addToSet: {score: {userId: someUser._id, score: 1}},
  $inc: {overallScore: 1},
  $addToSet: {votedOnBy: someUser._id},
  $inc: {timesVotedOn: 1}
});

Here's the actual document from mongo console (after the update):

{
  "_id" : "bKXXrpYmppFBfq9Kx",
  "title" : "This Is a Title",
  "body" : "Blah Blah Blah Body Goes Here",
  "userId" : "W9YEs84QFhZzJeB6j",
  "author" : "Users Name",
  "timestamp" : ISODate("2016-06-07T20:37:05.775Z"),
  "votedOnBy" : [
    "W9YEs84QFhZzJeB6j"
  ],
  "timesVotedOn" : 1
}

Notice that overallScore and score are not there at all.

I'm new to Meteor and Mongo (perhaps that's obvious). Does anyone know what I'm doing wrong here? Or what I need so that I may do this update right?

It's important to remember that the modifier is just an object. The following object literal:

{
  a: 1, b: 1,
  a: 2, b: 2
}

evaluates to:

{ a: 2, b: 2 }

because the keys are assigned twice, and the last write wins.

In your code, the same idea applies to the $addToSet and $inc keys. To fix it, write your update like this:

Ideas.update("bKXXrpYmppFBfq9Kx", {
  $addToSet: {
    score: { userId: someUser._id, score: 1 },
    votedOnBy: someUser._id
  },
  $inc: {
    overallScore: 1,
    timesVotedOn: 1
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM