猫鼬findOneAndUpdate Upsert _id是否为null? [英] Mongoose findOneAndUpdate Upsert _id null?

查看:85
本文介绍了猫鼬findOneAndUpdate Upsert _id是否为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有一个方法可以创建或更新策略文档.搜索并尝试使用不同的技术,例如,我想出了一个null _id用于我的文档.使用findByIdAndUpdate具有类似的效果.

I'd like to have a single method that either creates or updates a document for a policy. Searching and trying different techniques like this one, I have come up with a null _id for my document. Using findByIdAndUpdate has a similar affect.

我看到一个文档插入了集合,但是_id字段为空:

I see a document inserted in the collection, but the _id field is null:

exports.savePolicy = function (plcy, callback) {
    console.log('priority is : ' + plcy.priority)
    try {
        var policy = new Policy(plcy);
        var query = {_id: plcy._id};  //this may be null
        var update = {
            name: plcy.name || defaults.policyDefaults.name,
            longDescription: plcy.longDescription || defaults.policyDefaults.longDescription,
            shortDescription: plcy.shortDescription || defaults.policyDefaults.shortDescription,
            priority: plcy.priority, colorHex: plcy.colorHex || defaults.policyDefaults.colorHex,
            settings: plcy.settings || [],
            parentPolicyId: plcy.parentPolicyId || null
        }

        Policy.findOneAndUpdate(query, update, {upsert: true}, function (err, data) {
            callback(err, data);
        });

    } catch (e) {
        log.error('Exception while trying to save policy: ' + e.message);
        callback(e, null);
    }

是否可以做一些事情来使_id在不更新时不为空?

Is there something that can be done to get the _id not to be null when its not an update?

推荐答案

null在MongoDB中是有效的_id值,因此,如果您不希望在新文档中使用它,则必须确保null值在query中用新的ObjectID替换:

null is a valid _id value in MongoDB, so if you don't want it used in new docs you must ensure that a null value is replaced with a new ObjectID in query:

var query = {_id: plcy._id};
if (!query._id) {
    query._id = new mongoose.mongo.ObjectID();
}

// the rest stays the same...

这篇关于猫鼬findOneAndUpdate Upsert _id是否为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆