我目前正在使用nodeJs和mongoose,我想填充一个子文档
这是我的主要模特
var postSchema = require('./post.js');
var blogSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
postSchema: [postSchema]
});
var blog = mongoose.model('blog', blogSchema);
module.exports = blog;
这是帖后子文档
var mongoose = require('mongoose');
var postSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
rol: {
type: String,
required: true
}
});
var post = mongoose.model('post', post);
module.exports = post;
我想添加几个' post'在博客里面#39;架构,但我不知道如何,我试着通过我现在正确地填充它来填充它!我读到了关于“填充”的信息。关于猫鼬,但我根本不理解它,有人可以解释一下吗?
答案 0 :(得分:0)
你不能在猫鼬中使用外部Eschema数组。您必须在同一个文件中定义它们,或者只保存_id的数组并创建一个集合appart。
检查mongoose文档。他们谈到了这一点:http://mongoosejs.com/docs/2.7.x/docs/embedded-documents.html
var mongoose = require('mongoose');
var blogPost = new mongoose.Schema({
name: {
type: String,
required: true
},
rol: {
type: String,
required: true
}
});
var blog = new mongoose.Schema({
name: {
type: String,
required: true
},
postList: [blogPost]
});
mongoose.model('blog', blogSchema);
module.exports = blog;
var Blog = mongoose.model('blog');
// create a blog post
var theBlog = new Blog();
// create a comment
theBlog.postList.push({ title: 'My comment' });
theBlog.postList.save(function (err) {
if (!err) console.log('Success!');
});
希望它可以帮到你