My user schema is the below.
var userSchema=mongoose.Schema({
//name:{type:String},
username: {type:String, required:true, unique:true},
password: {type:String, required:true},
habit: {type:Object, required:true}
});
However, when I save new user (newbie) to mongoDB, only habit field is not saved.
var newbie=new User({
username:username,
password:password,
habit:{}
});
console.log(newbie);
The result of the console.log(newbie) is "{ _id: ~~~????, username: 'babo', password: '1234' }", which does not contain habit field... How can I add habit?
By default mongo doesn't save empty objects. So if you want to save an empty object you have to pass a second parameter { minimize: false }
to your Schema
.
Use this code. This should solve your problem.
var userSchema=mongoose.Schema({
//name:{type:String},
username: {type:String, required:true, unique:true},
password: {type:String, required:true},
habit: {type:Object, required:true}
}, { minimize: false });