Search code examples
mongodbmongoosemongodb-queryobjectid

Mongoose - find by referenced field _id


Collection Schema

const notificationsSchema = new mongoose.Schema({
  content: {
    type: String,
    required: true,
    maxlength: 1000
  },
  recipient: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  }
 }
});

Corresponding database entry

{
  "_id" : ObjectId("607c1ebc3c2e16b610d74464"),
  "content" : "Test Content",
  "recipient" : "607c1e2c0bb25343e53abf45" <--- Existing _id of a user
}

Trying to find by recipient field

deleteUser: combineResolvers(async (_, { id }) => {
      try {
        const user = await User.findById(id);
        console.log(user.id); <-- returns 607c1e2c0bb25343e53abf45
        
        // Option 1
        const notification = await Notification.findOne({ recipient: user.id }); 
        console.log(notification); <-- returns null

        // Option 2
        const userId = mongoose.Types.ObjectId(user.id);
        const notificationObjectId = await Notification.findOne({ recipient: userId }); 
        console.log(notificationObjectId); <-- returns null

        // Working alternative
        const notificationAlternative = await Notification.findOne({ content: "Test Content" });
        console.log(notificationAlternative); <-- returns the correct document

        return true;
      } catch (error) {
        throw error;
      }
    })  

Just to clarify, I am not trying to find the user by the recipient field, I am trying to find the notification document by the recipient field. Why can I not retrieve the document by the recipient id? What am I missing?


Solution

  • The error most probably would be because of difference in the datatypes while executing const notification = await Notification.findOne({ recipient: user.id }); . Check the datatype of user.id and need to convert to string user.id.toString()