Home > database >  NodeJs: how to assign additional objects to mongoose query response JSON
NodeJs: how to assign additional objects to mongoose query response JSON

Time:05-20

Using mongoose I am querying a list of posts and would like to determine whether or not the user has liked the image or not within the query function by adding a boolean to the response JSON. I am trying to do this in a for loop.

However, when I console.log(), the post with the field returns correctly but does not amend it to the JSON.

My function:

function(req, res) {
    var isLiked, likeCount;
      Post
      .find(/* Params */)
        .then(posts => { 

             for (var index in posts) {
               
                posts[index].isLiked = posts[index].likes.includes(req.headers.userid)

                console.log(posts[index])   // does not show 'isLiked' field in JSON
                console.log(posts[index].isLiked)   // response is correct
            }
            res.send(posts) // does not have 'isLiked field
        })
},

Post schema:

var postSchema = new Schema({
    userId: {
        type: String,
        required: true
    },
    caption: {
        type: String,
        required: false
    },
    likes: [{
        type: String,
    }]
});

CodePudding user response:

Cuz

Post.find()

is not return an object, you can set prop isLiked to posts[index] but it's private. Easy way to fix it is use lean() method to get return object

Post.find().lean()
.then(//do what you want)

CodePudding user response:

To add properties to queries objects you should convert them to JS objects:

function getPosts(req, res) {
  Post.find(/* Params */).then((posts) => {
    const result = [];
    for (const post of posts) {
      const postObj = post.toObject();
      postObj.isLiked = postObj.likes.includes(req.headers.userid);
      result.push(postObj)
    }
    res.send(result);
  });
}
  • Related