Javascript Meteor中基于嵌套文档自定义id的条件upsert
这是行不通的,但希望这一点和满嘴的标题能让人明白这一点Javascript Meteor中基于嵌套文档自定义id的条件upsert,javascript,mongodb,meteor,mongodb-query,Javascript,Mongodb,Meteor,Mongodb Query,这是行不通的,但希望这一点和满嘴的标题能让人明白这一点 function addToDB(account_id) { obj = {}; if (!Accounts.findOne({account_id: account_id})) obj.createdAt = new Date().valueOf(); obj.account_id = account_id; Accounts.upsert({account_id: account_id}, {$set:
function addToDB(account_id)
{
obj = {};
if (!Accounts.findOne({account_id: account_id})) obj.createdAt = new Date().valueOf();
obj.account_id = account_id;
Accounts.upsert({account_id: account_id}, {$set: obj});
}
我需要使用account_id而不是MongoDB对象id,因此它必须是可索引/唯一的。如果它是一个更新,createdAt不应该改变
已更新,因此它可以在原始上下文中工作,但我更喜欢我评论的解决方案,而不是正确的答案。我怀疑minimongo方面是否支持这一点,但您始终可以在服务器上实现逻辑并发布该方法。但MongoDB提供了一个运算符,其目的是仅将该值应用于“upsert”实际上插入新文档时执行的更新:
Accounts.upsert(
{ "account_id": obj.account_id },
{
"$setOnInsert": { "created_at": new Date() },
"$set": obj // account_id would be automatically added but it doesn't matter
}
))
当然,假定obj
尚未包含在处创建的字段,并且您想要的数据实际上是BSON“Date”类型,而不是历元时间戳(BSON Dates实际上在内部存储为历元时间戳),否则使用.valueOf()进行转换
如您的示例所示。这似乎有效。:)<代码>Accounts.upsert({account\u id:account\u id},{$setOnInsert:{'createdAt':new Date().valueOf()},$set:obj})代码>