Search code examples
node.jsmongodbloopbackjs

Loopback + mongoDB: Can't find extended user


I am using Loopback 3.0 with MongoDB connector. In a REST method exposed somewhere, I need to access the currently logged user and make some updates on it.

I have extended the base User model, calling it appUser, the login works, and I can get the token (after I changed the token model to point to the appUser) of a logged user. The model is the following one:

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

I need to access the user profile, in order to update it. But when I query it, I get null as result.

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

But if I run the same query from Robo3T on MongoDB, it works.

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

What am I doing wrong?

Thank you, Massimo


Solution

  • You didn't call the user so that should be the case, also in your callback you are passing null and not your user result. However I don't get where the res variable came from.

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

    I don't how you calling your callback but i think you can manage this. If you still have no result try changing _id to id