Home > front end >  Finding nested array objects with mongoose
Finding nested array objects with mongoose

Time:08-21

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?

CodePudding user response:

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

CodePudding user response:

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);
        }
    }
);
  • Related