如何在 mongoose 中正确嵌入文档?
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
学习了一个简单应用的教程,在尝试从中创建其他东西并了解 Mongoose 模式时,我在尝试使用嵌入文档时遇到错误,方法是之前应用定义模型的方式
我遇到了这个错误
throw new TypeError('Undefined type ' + name + '
at array `' + path
+
TypeError:数组 comments
处未定义类型 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);
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:数组 comments
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);