skip to Main Content

I have a user collection like this

{
  "_id": {
    "$oid": "62fe22f5d37c317701922d66"
  },
  "name": "Fahim Faisal",
  "email": "[email protected]",
  "password": "$2a$12$bkjeD.GesX4f7BNVF7C0CuKkkTyQA19kv6SAWuhObmPlAB11Tz9dy",
  "notes": [],
  "folders": [
    {
      "_id": {
        "$oid": "62fe22f5d37c317701922d67"
      },
      "name": "My Notes",
      "notes": []
    },
    {
      "_id": {
        "$oid": "62fe22f5d37c317701922d68"
      },
      "name": "Todos",
      "notes": []
    },
  ],
  "__v": 0
}

I want to check if an exact item in folders exists or not.

What I have tried so far

User.findOne(
    { _id: req.userId },
    {
        folders: {
            $elemMatch: {
                _id,
            },
        },
    },
    (err, system) => {
        if (err) {
            console.log(err);
        } else {
            console.log(system);
        }
    }
);

It doesn’t return the exact item. It returns this

{
  _id: new ObjectId("62faf0c424411076eb9b80e6"),
  folders: [
    {
      _id: new ObjectId("6302110a230f9123c1110273"),
      name: 'My Notes',
      notes: []
    },
    {
      _id: new ObjectId("6302110a230f9123c1110274"),
      name: 'Todos',
      notes: []
    },
    {
      _id: new ObjectId("6302110a230f9123c1110275"),
      name: 'Projects',
      notes: []
    },
    {
      _id: new ObjectId("6302110a230f9123c1110276"),
      name: 'Journals',
      notes: []
    },
    {
      _id: new ObjectId("6302110a230f9123c1110277"),
      name: 'Reading list',
      notes: []
    }
  ]
}

What should I do to get the exact item in the folders array exists or not?

2

Answers


  1. You should specify an Id in the elemMatch. For example something like this

    User.findOne(
        { _id: req.userId },
        {
            folders: {
                $elemMatch: {
                    _id:ObjectId('String Id'),
                },
            },
        },
        (err, system) => {
            if (err) {
                console.log(err);
            } else {
                console.log(system);
            }
        }
    );
    
    Login or Signup to reply.
  2. Add the $elemMatch filter for folders in the first object parameter, and with $ (projection) to limit and return the first (matched) item of folders array.

    Assume that i_d is ObjectId type.

    User.findOne(
        { 
            _id: req.userId,
            folders: {
                $elemMatch: {
                    _id: _id
                }
           }
        },
        {
            "folders.$": 1
        },
        (err, system) => {
            if (err) {
                console.log(err);
            } else {
                console.log(system);
            }
        }
    );
    

    Demo @ MongoPlayground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search