猫鼬:如何仅在保存数据时设置默认值(获取数据时不设置默认值)?

时间:2018-11-12 07:17:41

标签: javascript node.js mongodb mongoose

假设我有一个包含默认值的字段,我只想在保存()数据时使用此默认值,但是如果我获取的数据不包含默认值,我就不想看到默认值包括所需字段

//ignore any syntax or any other errors
let dataSchema = new mongoose.Schema({
    createdAt: {
        type: Date,
        default: Date.now
    },
    ....
})

let dataSchemaWithoutDefault = new mongoose.Schema({
    createdAt: Date
        ....
})

let dataModelWithoutDefault = mongoose.model("data", dataSchemaWithoutDefault)
let record = dataModelWithoutDefault.save() //createdAt doesn't present

//let's fetch data but with the default value enabled
let dataModel = mongoose.model("data", dataSchema)
dataModel.find().then(data => console.log(data))

//this with console data with default values, but I need a typical copy from the real collection
//[{createaAt:2018-11-12T06:54:50.119Z},...]

1 个答案:

答案 0 :(得分:0)

在保存方法中使用回调函数

   dataModelWithoutDefault.save(function (err, schema) {
    if (err) {
        response.status(500).send(err);
    } else {
        //use your default value
    }
})