假设我有一个包含默认值的字段,我只想在保存()数据时使用此默认值,但是如果我获取的数据不包含默认值,我就不想看到默认值包括所需字段
//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},...]
答案 0 :(得分:0)
在保存方法中使用回调函数
dataModelWithoutDefault.save(function (err, schema) {
if (err) {
response.status(500).send(err);
} else {
//use your default value
}
})