最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I properly embed documents in mongoose? - Stack Overflow

programmeradmin2浏览0评论
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({
    ments  : [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 ments

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({
    ments  : [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 ments

Share Improve this question edited Dec 14, 2020 at 5:40 Minal Chauhan 6,15812 gold badges23 silver badges41 bronze badges asked Apr 15, 2017 at 18:05 totalnoobtotalnoob 2,74110 gold badges39 silver badges72 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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({
    ments  : [CommentSchema]
});


module.exports.Comment = mongoose.model('Comment', CommentSchema);
module.exports.Post = mongoose.model('Post', PostSchema);
发布评论

评论列表(0)

  1. 暂无评论