node.js - populate embedded document on mongoose nodejs -
i'm working nodejs , mongoose , want populate sub-document
this main model
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;
this post sub-document
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;
and want add several 'post' inside 'blog' schema, don't know how, tried populating i'm doing properly! read 'populate' on mongoose i'm not understanding @ all, can explain it?
you cannot use arrays of external eschemas in mongoose. must define them in same file, or save array of _id´s , create collection appart.
check mongoose docs. talk that: 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 blog post var theblog = new blog(); // create comment theblog.postlist.push({ title: 'my comment' }); theblog.postlist.save(function (err) { if (!err) console.log('success!'); });
hope may you
Comments
Post a Comment