Search code examples
javascriptmongoosemongoose-schema

How do I properly embed documents in mongoose?


var mongoose = require('mongoose');

var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

var Comment = mongoose.model('Comment', new Schema({
    title     : String,
    body      : String,
    date      : Date
}))

var Post = mongoose.model('Post', new Schema({
    comments  : [Comment]
}))

module.exports.Comment = Comment
module.exports.Post = Post

Followed a tutorial for a simple app, and while trying to create something else off of it and learning about Mongoose schemas I get an error trying to use embedded documents with the way the previous app defined models

I'm getting this error

throw new TypeError('Undefined type ' + name + ' at array `' + path +

TypeError: Undefined type model at array comments


Solution

  • To embed a document you need to pass its schema in the referencing document. For that, you can separately store the schema in variable as an intermediate step and later use it to define model.

    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    var ObjectId = Schema.ObjectId;
    
    var CommentSchema = new Schema({
        title     : String,
        body      : String,
        date      : Date
    });
    
    var PostSchema = new Schema({
        comments  : [CommentSchema]
    });
    
    
    module.exports.Comment = mongoose.model('Comment', CommentSchema);
    module.exports.Post = mongoose.model('Post', PostSchema);