I have a model that looks like:
var CompanySchema = new Schema({
name: String
, logoUrl: String
, created: {
type: Date,
default: new Date().toUTCString()
}
, deleted: {
type: Date,
default: null
}
});
I want to have a field called id
as well (this is on top of the _id
that already gets added). So how can I create the id
field and have it automatically assigned to the value of _id
?
var mongoose = require('mongoose'); module. exports = mongoose. model('User',{ id: String, username: String, password: String, email: String, firstName: String, lastName: String }); It will automatically creates new "users" collection.
Mongoose will then set createdAt when the document is first inserted, and update updatedAt whenever you update the document using save() , updateOne() , updateMany() , findOneAndUpdate() , update() , replaceOne() , or bulkWrite() .
You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.
_id field is auto generated by Mongoose and gets attached to the Model, and at the time of saving/inserting the document into MongoDB, MongoDB will use that unique _id field which was generated by Mongoose.
CompanySchema.pre('save', function(next) {
this.id = this._id;
next();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With