【问题标题】:Loopback + mongoDB: Can't find extended userLoopback + mongoDB:找不到扩展用户
【发布时间】:2018-03-19 16:17:22
【问题描述】:

我正在使用带有 MongoDB 连接器的 Loopback 3.0。 在某处公开的 REST 方法中,我需要访问当前登录的用户并对其进行一些更新。

我扩展了基本用户模型,将其命名为 appUser,登录有效,并且我可以获得登录用户的令牌(在我将令牌模型更改为指向 appUser 之后)。模型如下:

{
  "name": "appUser",
  "plural": "appUsers",
  "base": "User",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "gender": {
      "type": "string",
      "enum": [
        "M",
        "F"
      ]
    },
    "birthDate": {
      "type": "Date"
    }
  },
  "validations": [],
  "relations": {},
  "acls": []
}

我需要访问用户个人资料才能对其进行更新。但是当我查询它时,我得到 null 作为结果。

const User = app.models.appUser;

User.findOne({
    where: {
        _id: ObjectId("5aae7ecd2ed1b11b1c09cf25")
    }
}, (err, user) => {
    if (err || res == null) {
        console.log("Error updating the user ");
        const error = {
            "name": "Database error",
            "status": 500,
            "message": "Can't access the database."
        }
        callback(error, null, null);
    } else {
        //Whatever
    }
});

但如果我在 MongoDB 上从 Robo3T 运行相同的查询,它就可以工作。

db.getCollection('appUser').find({"_id": ObjectId("5aae7ecd2ed1b11b1c09cf25")})

我做错了什么?

谢谢你, 马西莫

【问题讨论】:

    标签: node.js mongodb loopbackjs


    【解决方案1】:

    你没有打电话给用户,所以应该是这样,在你的回调中你传递的是 null 而不是你的用户结果。但是我不知道 res 变量的来源。

    const User = app.models.appUser;
    
    User.findOne({
        where: {
            _id: ObjectId("5aae7ecd2ed1b11b1c09cf25"),
        }
    }, (err, user) => {
        if (err) {
          console.log("Error updating the user", err); // logs the app error
          const error = {
                "name": "Database error",
                "status": 500,
                "message": "Can't access the database."
            }
          callback(error, null); // passes your custom error
        }
        console.log("APP USER", user);
        callback(null, user);
    });
    

    我不知道你如何调用你的回调,但我认为你可以做到这一点。 如果仍然没有结果,请尝试更改_id to id

    【讨论】:

      猜你喜欢
      • 2019-07-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-19
      • 1970-01-01
      • 1970-01-01
      • 2018-03-07
      • 1970-01-01
      • 2015-09-08
      相关资源
      最近更新 更多