【问题标题】:How do I properly embed documents in mongoose?如何在猫鼬中正确嵌入文档?
【发布时间】:2017-09-11 18:34:18
【问题描述】:
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

按照一个简单应用程序的教程,在尝试创建其他东西并学习 Mongoose 模式时,我在尝试使用嵌入文档时遇到错误,就像以前的应用程序定义模型的方式一样

我收到了这个错误

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

TypeError:未定义类型 model 位于数组 comments

【问题讨论】:

    标签: javascript mongoose mongoose-schema


    【解决方案1】:

    要嵌入文档,您需要在引用文档中传递其架构。为此,您可以将模式单独存储在变量中作为中间步骤,然后使用它来定义模型。

    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);
    

    【讨论】:

    • 我得到这个 throw new TypeError('Undefined type ' + name + ' at array ' + path + ^ TypeError: Undefined type model` at array comments
    • 但这不只是参考吗?我正在尝试做嵌入式文档
    猜你喜欢
    • 2015-09-06
    • 2012-05-11
    • 2011-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 1970-01-01
    相关资源
    最近更新 更多