Search code examples
node.jsmongodbmongoose

How to find value inside array of object with mongoose?


I have events system with different role for each event (same user could be different role in different events). I created collection of the users and this is the schema that i used:

const userSchema = new mongoose.Schema(
    {
    email: { type: String, required: true, unique: true },
    password: { type: String, required: true },

    permissions: [{
        eventId: { type: mongoose.Schema.Types.ObjectId, required: false, ref: 'Event' },
        role: { type: String, required: false }
    }]
    },
    {timestamps: true}
);

For check if the user is allowed to get this event I created middleware that need to check if the eventId is exist in the User collection under "permissions"

so this is the code that I was create:

const authorization = async (req, res, next) => {
    try {
        const eventId = req.params.id;
        
        const token = req.headers.authorization.split(' ')[1]
        const tokenDecoded = jwt.verify(token, process.env.JWT_SECRET);
        const userId = tokenDecoded.id
        console.log(userId)

        const userPermissionCheck = await User.find({ _id: userId, 'permissions.eventId': { $in: eventId } } );
        console.log(userPermissionCheck)
        

        next();
    } catch (error) {
        res.status(401).json({ message: 'Auth failed.' })
    }
}

My problem is that my find function in the authorization middleware is not working... What the correct way to search key of object in array with mongoose?

thanks


Solution

  • It seems that you are on the right track from your code, but you do not need the $in operator. You should be able to do the following:

     const userPermissionCheck = await User.find({ _id: userId, 'permissions.eventId': eventId });