Rohit Nishad
Rohit Nishad

Reputation: 2755

How to push data in MongoDB's array with mongoose

I have an empty array in MongoDB

And I want to push the Id in it.

router.put(
  "/like/:id",
  (req, res) => {
    User.findOne({ _id: req.user._id }).then(data => {
      if (data) {
        Post.update(
          { _id: ObjectId(req.params.id) },
          { $push: { likes: req.user._id } }
        );
      }
    });
  }
);

This code is not working on how I achieve this.

Upvotes: 1

Views: 423

Answers (1)

Debasis Das
Debasis Das

Reputation: 569

router.put (
  "/addlike/:id",
  passport.authenticate("jwt", {
    session: false
  }),
  (req, res) => {

   // use try-catch 
   try { 
    User.findOne({ _id: req.user._id }).then(data => {
      if (data) {
        Post.findOneAndUpdate(
          { _id: ObjectId(req.params.id) },
          { $push: { likes: req.user._id },
          { "new": true, "upsert": true} }
        );
      }
    });
   } catch(err){
    // handle error
    console.log('Error => ', err);
   }
  }
);

I have tested this in my local system ... working fine

Upvotes: 1

Related Questions