Home > Net >  How to update properties of object in Mongo Schema?
How to update properties of object in Mongo Schema?

Time:11-02

I have a mongo model like this:-

var mongoose = require("mongoose");

const postModel = new mongoose.Schema({
    postId: {
        type: String,
        unique: true,
        required: true
    },
    authorId: {
        type: String,
        required: true
    },
    post: {
        authorName: {
            type: String,
            required: true
        },
        heading: {
            type: String,
            required: true
        },
        message: {
            type: String,
            required: true
        },
        creationDate: {
            type: Date,
            required: true
        },
        image: {
            data: Buffer,
            contentType: String
        }, 
        likes: {
            type: Number
        },
        likedUsers: {
            type: Array
        },
        dislikes: {
            type: Number
        },
        hearts: {
            type: Number
        },
        dislikedUsers: {
            type: Array
        },
        heartedUsers: {
            type: Array
        },
        comments: {
            type: Array
        }
    }
});

module.exports = mongoose.model("postModel", postModel);

Now what i wanna do is take a record from this model and update the like property of the post object to what it previously was and increment that by 1.

How do I do that inside the api call body? My api call body looks like this for now:-

const express = require("express");
const router = express.Router();
const PostModel = require("../models/postModel");

router.post(`/api/like-post/`, (req, res) => {
    const { postId, postAuthorId, likeUserId } = req.body;

    //What to do here?
});

module.exports = router;

I am doing the api call from a react frontend on click of a like button.

Any and all help is greatly appreciated!

CodePudding user response:

Filter document by autherId and postId. Then use $inc to update your post like count by 1 and at last use $push to push likeUserId to the likedUsers array.

PostModel.update({
    postId: postId,
    authorId: postAuthorId
},
{
    $inc: {
          "post.likes": 1
     },
    $push: {
        "post.likedUsers": likeUserId 
    }
})

Sample mongo playground

  • Related