-1

In an "afterRemote"-Hook i want to find a specific model and change an attribute:

Team.afterRemote('prototype.__create__messages', function(ctx, message, next) {
    var Message = Team.app.models.message;

   // Promises.all not required, just for debugging (i removed other code)
    const promises = Promise.all( [
        Message.findById(message.id),
    ] )

    promises.then( function(result) {
        console.log("FOUND Message ", result);

        // here i'd like to change an attribute and save the model back to database
        console.log(typeof result.save); // will print undefined
    });

How could i manipulate the found entity and save it? Save()-Method is not present. All in all findById delivers a plain JSON-object, not a real PersistedModel-Instance.

The Model was defined as:

{ "name": "message", "base": "PersistedModel", "strict": false, "idInjection": false, "options": { "validateUpsert": true },

Database is a mongoDB.

itinance
  • 11,711
  • 7
  • 58
  • 98
  • `findById` actually must return a model instance. http://apidocs.strongloop.com/loopback/#persistedmodel-findbyid You should probably log a bug here: https://github.com/strongloop/loopback/issues/new – Sterex Jul 27 '17 at 18:50
  • Ah, looks like you have - https://github.com/strongloop/loopback/issues/3521 :) – Sterex Jul 27 '17 at 18:53

2 Answers2

2

Loopback model functions support promises as well. Your code can be rewritten as below.

var Message = Team.app.models.message;

Message.findById(message.id).then( function(result) {
    console.log("FOUND Message ", result);
    console.log(typeof result.save);
});
abskmj
  • 760
  • 3
  • 6
1

Solution:

console.log("FOUND Message ", result[0]);
console.log(typeof result[0].save);

Root cause: Please take a look of Promise.all documentation

Promise.all is fulfilled asynchronously. In all cases, the returned promise is fulfilled with an array containing all the values of the iterable passed as argument (also non-promise values).

So your case, result is an array like [messageObject].

Hope that my answer can help :)

haotang
  • 5,520
  • 35
  • 46