'NodeJs: how to assign additional objects to mongoose query response JSON

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,
    }]
});


Solution 1:[1]

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)

Solution 2:[2]

Use itertools.product(values, repeat=3) to get every combination of 3 values.

variants = [{
    'Field X': x,
    'Field Y': y,
    'Field Z': z,
} for x in values for y in values for z in itertools.product(values, repeat=3)]

If you have a dynamic list of fields, you can create the dictionary dynamically using dict(zip(...))

values=[True, False]
fields=['Field X', 'Field Y', 'Field Z']
variants = [
    dict(zip(fields, values))
    for values in itertools.product(values, repeat=len(fields))
]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Phạm Vỹ
Solution 2