简体   繁体   English

如何在MeteorJS中更新MongoDB集合上的子文档数组

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

I'm having a problem updating a mongo collection in Meteor. 我在Meteor中更新mongo集合时遇到问题。

Perhaps I just don't understand how $addtoset works. 也许我只是不了解$addtoset是如何工作的。

Here is my basic document, more or less this is in my fixtures.js where I initialize my project: 这是我的基本文档,或多或少都在我的fixtures.js ,用于初始化项目:

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): 这是mongo控制台中的实际文档(更新后):

{
  "_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. 注意, overallScore scorescore根本不存在。

I'm new to Meteor and Mongo (perhaps that's obvious). 我是Meteor和Mongo的新手(也许很明显)。 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. 在您的代码中,相同的想法也适用于$addToSet$inc键。 To fix it, write your update like this: 要解决此问题,请像这样编写update

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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