Lennert Hofman
Lennert Hofman

Reputation: 595

Comparing Express User with Mongoose Foreign Key

my mongoose model contains a foreign key for the model User. If a put, post or delete request comes in, I would like to check if the primary ID of the currently authenticated user is the same as the foreign key.

If i log the id's they are exactly the same, but the code seems to differ. Can someone please tell me the correct way to go about this? Thanks in advance.

Model

mongoose.model(
  'MyModel',
  mongoose.Schema({
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      required: true
    },
    ...
  })
)

Express Route

router.put('/models/:id', auth, (req, res, next) => {
  MyModel.findById(req.params.id, (err, model) => {
    if (err) return res.status(500).send({success: false, msg: 'Model not found'});
    if (req.user._id !== model.user) return res.status(500).send({sucess: false, msg: 'You did not create this model'});

    ...success...
  });
});

Upvotes: 0

Views: 198

Answers (1)

Shivam Pandey
Shivam Pandey

Reputation: 3936

In the model, you are storing the user as ObjectId and whenever you match it with the user in,

if (req.user._id !== model.user)

it always returns true because req.user._id a string type and model.user has ObjectId type. It is like

if ("5b9b69933fc1de058a4086ed" !== ObjectId("5b9b69933fc1de058a4086ed")

You can compare them by converting the user id to an ObjectId type.

import mongoose from 'mongoose';

if (!new mongoose.Types.ObjectId(user._id).equals(model.user))

Upvotes: 1

Related Questions