【问题标题】:Conditional upsert based on custom id of nested documents in Meteor基于 Meteor 中嵌套文档的自定义 id 的条件更新
【发布时间】:2014-09-12 21:26:10
【问题描述】:

这是行不通的,但希望这个和满嘴的标题能说明问题

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 不应更改。

已更新,因此它可以在原始上下文中使用,但我更喜欢我评论的解决方案而不是正确答案。

【问题讨论】:

    标签: javascript mongodb meteor mongodb-query


    【解决方案1】:

    我怀疑这在 minimongo 方面是否受支持,但您始终可以在服务器上实现逻辑并发布方法。但是 MongoDB 提供了一个 $setOnInsert 运算符,其目的是仅将该值应用于“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 还没有包含 created_at 字段,并且您想要的数据实际上是 BSON“日期”类型而不是纪元时间戳(无论如何,BSON 日期实际上在内部存储为纪元时间戳),否则使用.valueOf() 进行转换,如您的示例所示。

    【讨论】:

    • 这似乎行得通。 :) Accounts.upsert({account_id: account_id}, {$setOnInsert: {'createdAt': new Date().valueOf()}, $set: obj});
    猜你喜欢
    • 2016-04-14
    • 1970-01-01
    • 2017-06-09
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    相关资源
    最近更新 更多