Warm tip: This article is reproduced from serverfault.com, please click

MongoDB object type is not saved

发布于 2020-11-28 07:28:06

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?

Questioner
주혜민
Viewed
0
Nouman Dilshad 2020-11-28 15:37:57

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 });