Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 841
totalnoob Avatar asked Nov 29 '25 06:11

totalnoob


1 Answers

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);
like image 148
Talha Awan Avatar answered Nov 30 '25 20:11

Talha Awan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!