Henok Tesfaye
Henok Tesfaye

Reputation: 9560

Model.findOne is not working as expected?

[
  {
    "userId": "5bb6730721f28a295436b36e",
    "reputationNumber": 0,
    "questions": [],
    "answers": [],
    "id": "5bb6730721f28a295436b36f"
  },
  {
    "userId": "5bb6738c21f28a295436b370",
    "reputationNumber": 0,
    "questions": [],
    "answers": [],
    "id": "5bb6738c21f28a295436b371"
  }
]

I have 2 elements inside a model userDatas and i want to find a single userData by filtering with userId property.

This is what i did

Userdatas.findByUserId = function(req, res, cb) {
    const queryId = req.query.userId
    console.log("queryId: ",queryId);
    Userdatas.find({ userId: "5bb6738c21f28a295436b370"}, function(err, obj){
        console.log(obj);
        var userData = obj;
        cb(null, userData);
    });
}

Amazingly the the console output is,

    [ { userId: '5bb6730721f28a295436b36e',
    reputationNumber: 0,
    questions: List [],
    answers: List [],
    id: 5bb6730721f28a295436b36f },
  { userId: '5bb6738c21f28a295436b370',
    reputationNumber: 0,
    questions: List [],
    answers: List [],
    id: 5bb6738c21f28a295436b371 } ]

what i expect is,

{
    "userId": "5bb6738c21f28a295436b370",
    "reputationNumber": 0,
    "questions": [],
    "answers": [],
    "id": "5bb6738c21f28a295436b371"
  }

But the query works perfectly in robo mongo shell.

Upvotes: 2

Views: 240

Answers (1)

tashakori
tashakori

Reputation: 2441

in loopback "find" and "findOne" functions accept queries in this pattern: {where:{queryFilters}}

so, in your example, you can change it like this:

Userdatas.findByUserId = function(req, res, cb) {
    const queryId = req.query.userId
    console.log("queryId: ",queryId);
    Userdatas.findOne({ where:{userId: "5bb6738c21f28a295436b370"}}, function(err, obj){
        console.log(obj);
        var userData = obj;
        cb(null, userData);
    });
}

Open user-datas.json under options add "strictObjectIDCoercion": true property.

Upvotes: 2

Related Questions