0

When defining an array of objects in a Mongoose schema as so:

var mySchema = new mongoose.Schema({
    stuff : [ Object ]
});

When trying to save an instance of this object, with 'stuff' filled up with some objects, Mongoose gives the following error: "Object # has no method 'cast'"

What is the correct way to declare an array of objects in Mongoose?

3 Answers 3

1
var ObjectSchema = new mongoose.Schema({
    //your object schema
});

var mySchema = new mongoose.Schema({
    stuff : [ ObjectSchema ]
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but the sub-object is coming from an external source and I have no control over its layout. Its quite large, and I don't want to design a schema for it myself. I just want to have a single schema, for my data, with an array of these external objects in it.
1

Something like this should work

var mySchema = new mongoose.Schema({
stuff1 :{type:String},
stuff2 :{type:Number},
array :[{arraystuff1:{type:String}}]
});

Here is a link where you can find information about it http://mongoosejs.com/docs/guide.html

1 Comment

I can't accept my own answer till tomorrow, but I have figured it out and see below for a better solution. Basically, you don't need any of that "arraystuff1" stuff. Just having " array: [] " is enough.
0

Looking at it further, the way to do is is to not use the Object type provided by Mongoose, as that causes problems. Instead just define it as an array:

var mySchema = new mongoose.Schema({
    stuff : [ ]
});

This works, lets you put whatever you want into it and will save it correctly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.