Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to default an embedded document to null with mongoose

Lets say I have a schema with an embedded document called preferences that contains multiple values. I'm trying to have mongoose default the embedded document to null

For example here's how I've defaulted fields to null for basic types like Strings and Dates in the past.

var userSchema = new Schema({
name: {type: String, required: true},
preferences: {type: preferences, default: null}
});

var preferences: {
preference1: String,
preference2: String
}

How should I default the property preferences in the userSchema to be null on a new document's creation?

like image 900
Austin Davis Avatar asked Dec 29 '14 20:12

Austin Davis


1 Answers

var userSchema = new mongoose.Schema({
  name: {type: String, required: true},
  preferences: {type : { preference1 : String, preference2 : String}, default : null}
});

Tested with:

User.create({name : "Aladin"})
User.create({name : "Aladin", preferences : {preference1 : "Wunderlampen", preference2 : "Teppich" }})
like image 102
Kiechlus Avatar answered Oct 27 '22 10:10

Kiechlus