Mongoose upsert does not create default schema property

后端 未结 2 1215
闹比i
闹比i 2020-12-16 12:17

Example document Schema:

var CompanySchema = Schema({
    created: { type: Date, default: Date.now },
    modified: { type: Date, default: Date.now },
    ad         


        
相关标签:
2条回答
  • 2020-12-16 12:35

    You may use { "$setOnInsert": { value: 31 } } Doc

    Ref: https://groups.google.com/forum/#!topic/mongoose-orm/WuJSqxPX8T8

    syntax: findOneAndUpdate([query], [doc], [options], [callback]) Doc

    example:

    model.findOneAndUpdate(
          { username: 'john' },
          { "$setOnInsert": { points: '0' },
                $push: {
                "boards": {
                    "account":req.body.account,
                    "game":req.body.game                                        
                }
            }          
          { upsert: true},
          function(err, doc) {    
    
          });
    
    0 讨论(0)
  • 2020-12-16 12:36

    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.

    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.

    Mongoose 4.0 Update

    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( ...
    
    0 讨论(0)
提交回复
热议问题