Created
April 2, 2018 16:02
-
-
Save Alex-Shilman/dbc3c74a05c1c4b2b53eeffa8f0bc31c to your computer and use it in GitHub Desktop.
Using Mongoose multiple collections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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