Model.findOne无法正常工作?

时间:2018-10-04 21:14:46

标签: mongodb mongoose loopbackjs

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

我在模型userDatas中有2个元素,我想通过用userId属性过滤来查找单个userData。

这就是我所做的

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

令人惊讶的是,控制台输出是

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

我期望的是

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

但是该查询在robo mongo shell中可以完美运行。

1 个答案:

答案 0 :(得分:2)

在环回中,“ find”和“ findOne”函数以这种模式接受查询:{where:{queryFilters}}

因此,在您的示例中,您可以像这样更改它:

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

在选项下打开user-datas.json添加"strictObjectIDCoercion": true属性。