Mongoose associations

I am newbie. I am trying to join various collections to get some data. I can get post from creator and likes info, but how do I get posts with comments and comments using 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 scheme

 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 receive comment IDs, but I want to receive comments with their information. What am I doing wrong? json_object_image

+3


source to share


1 answer


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



0


source







All Articles