Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an automatic field in Mongoose?

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?

like image 422
Shamoon Avatar asked Apr 03 '12 21:04

Shamoon


People also ask

Does Mongoose create collection automatically?

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.

How are the createdAt and updatedAt fields getting created for a user object?

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() .

Can I set default value in Mongoose schema?

You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.

Does Mongoose auto generate ID?

_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.


1 Answers

CompanySchema.pre('save', function(next) {
  this.id = this._id;
  next();
});
like image 51
Shamoon Avatar answered Oct 06 '22 00:10

Shamoon