I am trying to create the model for my mongodb database using mongoose. This is what I am trying to do:
var Class = mongoose.model(\'Class\', {className: St
Explicitly defining the type rule on a property called type is allowed and won't throw an error. like this:
type: {type: String}
By default, if you have an object with key 'type' in your schema, mongoose will interpret it as a type declaration.
// Mongoose interprets this as 'loc is a String'
var schema = new Schema({ loc: { type: String, coordinates: [Number] } });
Changing the typeKey:
var schema = new Schema({
// Mongoose interpets this as 'loc is an object with 2 keys, type and coordinates'
loc: { type: String, coordinates: [Number] },
// Mongoose interprets this as 'name is a String'
name: { $type: String }
}, { typeKey: '$type' }); // A '$type' key means this object is a type declaration
Link: http://mongoosejs.com/docs/guide.html#typeKey
Now Mongoose supports subdocuments, which are the documented way to nest arrays,
var arraySchema = new Schema({
property: String
});
var objectSchema = new Schema({
arrays: [arraySchema]
});
Sources
http://mongoosejs.com/docs/schematypes.html
I got a similar issue using mongoose 5.7.0+ using double nested schema.
Except it wasn't related to the keyword type
but a mongoose validation bug.
https://github.com/Automattic/mongoose/issues/8472
Temporary workaround: Use Schema.Types.Mixed
for the subschema
Try changing the class definition to :
var classSchema = mongoose.Schema({className: String, marks: [{type: Number}], grades: [{type: Number}]});
var userSchema = mongoose.Schema({email: String, classes: [classSchema] });
var User = mongoose.model('User',userSchema);
This is required since mongoose is not able to parse the object without a related schema. Now when you create a new Schema for the internal class object and refer it in the main userSchema mongoose should be able to parse your object.
Man, I had a similar issue creating an Schema like this:
QuestionnaireSchema = mongoose.Schema({
formId: Number,
name: String,
questions: [
{
type: String,
title: String,
alternatives:[{
label: String,
value: "Mixed"
}]
}
]
});
My mistake was that I am using "type" as a field name and this is reserved word in mongoose.
I just change:
type: String,
to
formType: String,
and that works.
see: https://github.com/Automattic/mongoose/issues/1760