Search code examples
javascriptnode.jsexpressmongoosepostman

findOne mongoose query is not working properly


I have used express to create this web-app. I also have mongoose model:

{
  username: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  notes: [{
    name: { type: String, required: true }
  }]
}

When I try to find object inside of array(Notes) ->

modelName.findOne({ "notes:" {$elemMatch: {"_id": req.body.id } }})
  .exec()
  .then(result => {
    console.log(result);
  })
  .catch(err => {
    console.log(err);
  });

I get whole model object of one user instead of one note. Here is the result which I get:

{
  "_id": "5c51dd8be279e9016716e5b9",
  "username": "user1",
  "password": "",
  "notes": [
    {
      "_id": "5c51dd8be279e901671gagag",
      "name": "name of note1"
    },
    {
      "_id": "5c51ff8be279e901671gagag",
      "name": "name of note"
    },
    {
      "_id": "5c51dd8be2131501671gagag",
      "name": "name of note"
    }
  ]
}

My expectation, however, is to receive something like this:

{
  "_id": "5c51dd8be279e901671gagag",
  "name": "name of note1"
}

P.S: It is not duplicate of this answer Mongoose Mongodb querying an array of objects. I have already tried to use code from that question, but it doesn't solve my problem


Solution

  • findOne() is working just fine. findOne() returns any document that matches the specified query, not part of a document. If you want just part of that document, you will have to get it in two parts...

    modelName.findOne({ "notes": {$elemMatch: {"_id": req.body.id } }})
    .exec()
    .then(result => {
      // Will get an array of notes whose _id === req.body.id
      const resNote = result.notes.filter(n => n._id === req.body.id);
      console.log(resNote);
    })
    .catch(err => {
    console.log(err);
    });
    

    See the documentation here. If you note, it mentions that the function " finds one document".