Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to match two fields in MongoDb but one is ObjectId

I am creating an Interactive platform and I decide to use MongoDB as my DB. I want only the blog owner who is signed in at that as the only person who can delete the blog but What I have currently is bypassing the criteria when using the token of another user
How can I match two fields in Model being one is objectId

My midlleware
It has to pass through authenticated first before proceeding to the next middleware


const blogowner = expressAsyncHandler(async (req, res, next) => {
  authenticated(req, res, async () => {
    try {
      const isblog = await Blog.find({
        $and: [{ _id: req.params.blogid }, { user: { $eq: req.user._id } }],
      });
      if (isblog) {
        next();
      } else {
        res.status(401).send({ ErrMessage: "action permission denied" });
      }
      console.log("blog owner found");
    } catch (error) {
      res.status(500).send({ ErrMessage: error.message });
    }
  });
});

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You don’t need to use MongoDB operators and cast ids to ObjectId, Mongoose will automatically do that for you, when you’re using Mongoose native methods like find(), findOne() for AND operations.

You can find the document like this.

const blogowner = expressAsyncHandler(async (req, res, next) => {
  authenticated(req, res, async () => {
    try {
      const isblog = await Blog.find({ _id: req.params.blogid, user: req.user._id })
      if (isblog) {
        next()
      } else {
        return res.status(401).send({ ErrMessage: 'action permission denied' })
      }
      console.log('blog owner found')
    } catch (error) {
      res.status(500).send({ ErrMessage: error.message })
    }
  })
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading