1

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.

1
  • findOne() in Mongoose returns a Query, not a Promise. You need to chain the exec method for you to get a promise i.e. User.findOne({ _id: req.user._id }).exec().then(...) or User.findById(req.user._id).exec().then(...) Commented Feb 20, 2020 at 11:23

1 Answer 1

1
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

Sign up to request clarification or add additional context in comments.

4 Comments

When i am use this code my VS code give me some syntax error.
@RohitNishad Do not copy paste whole code. follow logic. Use findOneAndUpdate Post.findOneAndUpdate( { _id: ObjectId(req.params.id) }, { $push: { likes: req.user._id }, { "new": true, "upsert": true} } );
@RohitNishad You have solved this problem by using my logic. Am i right ???
No, i just change few things. like use $addtoset in place of $push and remove User.findOne etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.