Example document Scheme:
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 use a common query handler to edit and create 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)); } }); };
But using this method, when a new document is inserted, the created , modified properties are not saved with the default values ββof Date.now . Now I can call Company.create depending on the availability of the identifier, but I wonder why upsert does not use the default values ββif the property does not exist in the new document?
I am using Mongoose version ~ 3.8.10,
strada
source share