如果使用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
}
});
答案 0 :(得分:0)
您需要展开{{1}}的查询参数:
upsert
您的查询中只有一个参数:MyCol.upsert({ userId: userId },{ $set: ... });
。由于userId
和c
正在发生变化,您还需要将它们包含在您的查询中:
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 })