猫鼬upsert不会创建默认架构属性 [英] Mongoose upsert does not create default schema property

查看:61
本文介绍了猫鼬upsert不会创建默认架构属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例文档架构:

var CompanySchema = Schema({
    created: { type: Date, default: Date.now },
    modified: { type: Date, default: Date.now },
    address: { type: String, required:true },
    name: { type: String, required:true }
});

我正在使用通用的请求处理程序来编辑和创建公司"文档:

I'm using a common request handler for edit and create of "Company" documents:

exports.upsert = function(req, res) {
    helper.sanitizeObject(req.body);
    var company = {
        name: req.body.name,
        address: req.body.address
    };
    var id = req.body.id || new mongoose.Types.ObjectId();
    var queryOptions = {
        upsert: true
    };
    Company.findByIdAndUpdate(id, company, queryOptions).exec(function(error, result) {
        if(!error) {
            helper.respondWithData(req, res, {
                data: result.toJSON()
            });
        } else {
            helper.respondWithError(req, res, helper.getORMError(error));
        }
    });
};

但是使用这种方法,当插入新文档时,createdmodified属性不会保存为默认值Date.now.现在,我可以根据id的存在来调用Company.create,但是我想知道如果新文档中不存在属性,为什么upsert不使用默认值?

But using this method, when a new document is inserted, created, modified properties are not saved with default values of Date.now. Now I can call Company.create depending on the existence of an id but I'm wondering why upsert does not use default values if a property does not exist on a new document?

我使用的是Mongoose版本〜3.8.10,

I'm using Mongoose version ~3.8.10,

推荐答案

发生了什么事,当调用任何"update"方法族(如findByIdAndUpdate)时,都没有使用Mongoose的验证,中间件或默认值. .只能通过调用savecreate来调用它们.

What's going on is that none of Mongoose's validation, middleware, or default values are used when calling any of the "update" family of methods, like findByIdAndUpdate. They're only invoked by calls to save or create.

之所以这样,是因为更新"调用实际上是传递给本机驱动程序,而Mongoose仅根据架构定义提供字段的类型转换.

The reason for this is that the "update" calls are effectively pass-throughs to the native driver, with Mongoose only providing type-casting of the fields based on the schema definition.

猫鼬4.0更新

猫鼬现在支持在updatefindOneAndUpdatefindByIdAndUpdate向上插入期间创建新文档时设置默认设置.将setDefaultsOnInsert选项设置为true以启用此功能.这将使用$setOnInsert运算符在插入时创建默认值.

Mongoose now supports setting defaults when a new document is created during an update, findOneAndUpdate, or findByIdAndUpdate upsert. Set the setDefaultsOnInsert option to true to enable this. This uses the $setOnInsert operator to create the defaults on insert.

var queryOptions = {
    upsert: true,
    setDefaultsOnInsert: true
};
Company.findByIdAndUpdate(id, company, queryOptions).exec( ...

这篇关于猫鼬upsert不会创建默认架构属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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