elisa
elisa

Reputation: 229

How to find an ID inside a document property (array) and return the populated information of that object

I have the following document in MongoDB. How can I find a specific ID inside the likes array and return the populated information of that object?

This is the document:

{ _id: ObjectId("60a90f0e1f4af802e8b893e6"),
  status: 'Available',
  likes: 
   [ ObjectId("60a8e0b9baa1572b847931ed"),
     ObjectId("60aa342cb6b39e3024453465") ],
  name: 'coba',
  age: '1 Year',
  __v: 0 }

This is the function I have tried but it's returning a 404 error, though as you can see the id actually exists in the likes array.

    const [foundUser] = await PetsModel.find(
      {
        likes: { $in: ["60a8e0b9baa1572b847931ed"] }
      },
      { likes: 1 }
    ).populate({
      path: 'likes',
      select: {
        __v: 0,
        createdAt: 0,
        updatedAt: 0,
        password: 0
      }
    });

    res.status(201).json({
      success: true,
      data: foundUser.likes
    });
  

Upvotes: 0

Views: 39

Answers (1)

Luciano Barreto
Luciano Barreto

Reputation: 76

There you are telling MongoDB to search a string, not an id. So you have to convert the string into an id so MongoDB can search it. The code should look like this:

const mongoose = require('mongoose');

const [foundUser] = await PetsModel.find(
      {
        likes: { $in: [ mongoose.Types.ObjectId("60a8e0b9baa1572b847931ed") ] }
      },
      { likes: 1 }
    ).populate({
      path: 'likes',
      select: {
        __v: 0,
        createdAt: 0,
        updatedAt: 0,
        password: 0
      }
    });

    res.status(201).json({
      success: true,
      data: foundUser.likes
    });

Upvotes: 1

Related Questions