byrdr
byrdr

Reputation: 5487

Mongoose nested schema CastError

I have the following data which contains a nested schema:

User Schema

(function userModel() {

var mongoose = require('mongoose');
var Entry    = require('./entry');
var Schema   = mongoose.Schema;

var usersSchema = new Schema({
    entries: [Entry]
});

module.exports = mongoose.model('Users', usersSchema);

})();

Entry Schema

(function entryModel() {
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var entrySchema = new Schema({
    timeStamp: {
        type: Date,
        default: Date.now
    },
    data : [Schema.Types.Mixed]
});

module.exports = mongoose.model('Entry', entrySchema);

})();

I'm returning the the following error:

errors: 
   { entries: 
      { [CastError: Cast to Array failed for value "[object Object]" at path "entries"]`

As far as I can tell this is the correct way to include subdocuments. Am I doing something wrong here?

Upvotes: 2

Views: 253

Answers (1)

Yuri Zarubin
Yuri Zarubin

Reputation: 11677

This line module.exports = mongoose.model('Entry', entrySchema); exports the model not the schema. You need to export entrySchema and use that to construct the userSchema

EDIT:

If you want to export both model and schema, you'd need to do something like

module.exports = {
  schema: entrySchema,
  model: mongoose.model('Entry', entrySchema)
}

In general however, you rarely ever need to export the actual model. This is because whenever you want to have access to that particular model in a different file, you would simply call mongoose.model('Entry') and get that model instance back. It is not necessary to call require('.path/to/model') just to get access to the model.

Upvotes: 3

Related Questions