如果找不到,请插入文档

时间:2016-08-02 03:37:43

标签: mongodb meteor

如果使用upsert不存在,则此Meteor服务器代码每次尝试在循环内插入不同的文档,它只插入第一个文档,但不插入以下内容,即使它们不同。我究竟做错了什么?感谢

MyCol = new Mongo.Collection('myCol');

MyCol.before.insert(function(userId, doc) {
  doc.userId = userId;
  doc.createdAt = Date.now();
});

//the following is inside a loop where C and date changes
MyCol.upsert({
  userId: userId
}, {
  $set: {
    a: 'A',
    b: 'B',
    c: C,
    date: date
  }
});

1 个答案:

答案 0 :(得分:0)

您需要展开{​​{1}}的查询参数:

upsert

您的查询中只有一个参数:MyCol.upsert({ userId: userId },{ $set: ... }); 。由于userIdc正在发生变化,您还需要将它们包含在您的查询中:

date

您甚至可能需要在查询中加入MyCol.upsert({ userId: userId, c: C, date: date }, { $set: { a: 'A', b: 'B', c: C, date: date }}); a,如果它们是文档唯一性的一部分。

或者,您也可以b.update()标记设置为upsert时使用true

MyCol.update(query,modifier,{ upsert: true })