Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Associations

I am a newbie. I'm trying to join different collections to get some data. I am able to get post creator and likes information, but how do I get posts with their comments and commentor information using the association in mongoose?

USER Schema

 const userSchema = mongoose.Schema({
     username: {
         type: String,
         minlength: [6, 'Minimum length of username must be 6 characters'],
         trim: true,
         lowercase: true,
         required: true,
         unique: true
     },
     email: {
         type: String,
         minlength: [6, 'Minimum length of email must be 6 characters'],
         trim: true,
         unique: true
     },
     password: {
         type: String,
         minlength: [6, 'Minimum length of password must be 6 characters'],
         required: true
     },
     tokens: [{
         access: {
             type: String
         },
         token: {
             type: String
         }
     }],
     posts: [{
         type: mongoose.Schema.Types.ObjectId,
         ref: 'post'
     }]
 }, {
     timestamps: true
 });

POST Schema

 const postSchema = mongoose.Schema({
     title: {
         type: String,
         trim: true,
         required: true
     },
     body: {
         type: String,
         trim: true,
         required: true
     },
     _creator: {
         type: ObjectId,
         ref: 'user'
     },
     comments: [{
         type: ObjectId,
         ref: 'comment'
     }],
     likes: [{
         type: mongoose.Schema.Types.ObjectId,
         ref: 'user'
     }]
 }, {
     timestamps: true
 });

COMMENT Schema

 const commentSchema = mongoose.Schema({
     title: {
         type: String,
         trim: true
     },
     _creator: {
         type: ObjectId,
         ref: 'user'
     },
     _post: {
         type: ObjectId,
         ref: 'post'
     }
 }, {
     timestamps: true
 });

 // get posts from all users
 postRoutes.get('/', authMiddleware, async(req, res) => {
     try {
         const user = req.user;
         const posts = await Post.find({})
             .populate('_creator likes comments')
             .sort({
                 createdAt: -1
             })
             .limit(1);

         return res.send(posts);

     } catch (e) {
         return res.status(400).send(e);
     }
 });

I only get comment IDs but I want comments with their information. What am I doing wrong? json_object_image

like image 511
Firangi Dev Avatar asked Oct 29 '22 06:10

Firangi Dev


1 Answers

You are looking for Mongoose populate Here is the link to the docs http://mongoosejs.com/docs/populate.html

like image 57
Rushi Suthar Avatar answered Nov 15 '22 06:11

Rushi Suthar