Skip to content

Instantly share code, notes, and snippets.

@Alex-Shilman
Created April 2, 2018 16:02
Show Gist options
  • Save Alex-Shilman/dbc3c74a05c1c4b2b53eeffa8f0bc31c to your computer and use it in GitHub Desktop.
Save Alex-Shilman/dbc3c74a05c1c4b2b53eeffa8f0bc31c to your computer and use it in GitHub Desktop.
Using Mongoose multiple collections
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var commentSchema = new Schema({
comment: type:String,
user_id:{
type:Schema.Types.ObjectId, ref:'User'
},
is_active :1
},{ collection: 'comment'});
cosnt Comment = mongoose.model('Comment', commentSchema);
module.export = Comment;
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var postSchema = new Schema({
post: type:String,
user_id:{
type:Schema.Types.ObjectId, ref:'User'
},
is_active :1
},{ collection: 'post'});
cosnt Post = mongoose.model('Post', postSchema);
module.export = Post;
const User = require('./user');
User.find()
.populate('comments posts') // multiple path names in one requires mongoose >= 3.6
.exec(function(err, usersDocuments) {
// handle err
// usersDocuments formatted as desired
});
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
const userSchema = new Schema({
nick_name:{type:String},
email: {
type: String,
trim: true,
required: '{PATH} is required!',
index: true,
},
comments: [{ type: Schema.Types.ObjectId, ref:'Comment' }],
posts: [{ type: Schema.Types.ObjectId, ref:'Post' }]
}, {timestamps: true});
const User = mongoose.model('User', userSchema);
module.exports = User;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment