Default value not set while using Update with Upsert as true

后端 未结 2 1639
北恋
北恋 2021-01-18 11:30

I have the following model for users:

var UserSchema = new mongoose.Schema({

    name: String,
    dob: Date,
    sex: String,
    photo: String,
    email:         


        
2条回答
  •  渐次进展
    2021-01-18 11:58

    For adding defaults to your document if it was created with findOneAndUpdate (it didn't exist before the query) and you did not provide the field in the update you should use setDefaultsOnInsert.

    When upsert and setDefaultsOnInsert are both true, the defaults will be set if the record is not found and a new one is created. This skips the workflow of having to check if the record exists and if not then creating a new one with 'save' just to make sure defaults are set.

    I have had the same issue(record created with findOneAndUpdate with upsert: true) and the default value for a field was not added to the record, even though it was in the schema. This is only in regards to adding defaults when using findOneAndUpdate to create documents, not for skipping the update of the 'created' field.

    i.e. User.findOneAndUpdate({email: user.email}, user, {upsert: true, setDefaultsOnInsert:true}, ...)

提交回复
热议问题