mhendek
mhendek

Reputation: 273

Mongoose- How can I create a collection with the default values?

I am creating a schema with the following code;

var Repository = require('./base/Repository'); 
var Connection = require('./base/Connection');

    var scm = Repository.schema({
        userId : String,
        text: String,
        date: Number });

    scm.index({date:1}); scm.index({userId:1});

    var repo = Repository.create('Feedback', scm, Connection);

    module.exports = new repo();

But I want to give default values for the fields while creating this schema. For example I want something like that ;

var scm = Repository.schema({
        userId : 12334455,
        text: hello world,
        date: 19.04.2018 });

How can I manage this with Mongoose ?

Upvotes: 1

Views: 2286

Answers (2)

Alexander Mills
Alexander Mills

Reputation: 99970

Try this: http://mongoosejs.com/docs/defaults.html

you may wish to use the setDefaultsOnInsert option.

Upvotes: 2

Muhammad Usman
Muhammad Usman

Reputation: 10148

You can always specify default values while defining your schema. Like

Repository.schema({
userId : { type: String, default: '12334455' },
text: { type: String, default: 'Xyx' },
date: { type: String, default: 12334455 }
})

Here is documentation

Upvotes: 1

Related Questions