Home > Enterprise >  How to match two fields in MongoDb but one is ObjectId
How to match two fields in MongoDb but one is ObjectId

Time:09-21

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

CodePudding user response:

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 })
    }
  })
})
  • Related