1
votes

I have a model called ModelA which uses base class Model, not PersistedModel. ModelA contains an existing Model instance which contains the following document.

{
    "_id" : ObjectId("5cf34da5265db517d8e366d3"),
    "userId" : ObjectId("5cf34da5265db517d8e366d0"),
    "providers" : [ 
        "123456789", 
        "1598763690", 
        "1407850217", 
        "1720082597"
    ],
    "countByType" : {
        "doctors" : 3,
        "laboratories" : 0,
        "hospitals" : 0,
        "imagingCenters" : 0,
        "other" : 2
    }
}

The problem I am facing right now is how to save the data into existing model instance.

 var modelInstance = new ModelA({userId: user.id, providers: ['111111111','222222222'], countByType: userProviderData.countByType});
           UserProvider.save({validate: false, throws: false },function(err, user) {
             if(err) {

               console.log('Errorsssssss ',err);
             } else {
               console.log(user);
             }
           });

Checked the below documentation, but this is creating new instance, instead of saving into existing Model.

https://apidocs.strongloop.com/loopback/v/1.5.1/#model-save-options-callback

Any help would be really appreciated.

1
What version of loopback are you using? - Farid Nouri Neshat
@farid-nouri-neshat : loopback 3 - Vishnu
What is UserProvider? - Ebrahim Pasbani
The answer of @FaridNouriNeshat is correct. Also you didn't put _id field in your modelInstance. You just did userId - Ebrahim Pasbani
In line new ModelA({userId: user.id, providers: ['111111111','222222222'], countByType: userProviderData.countByType});, I don't see field id - Ebrahim Pasbani

1 Answers

2
votes

You should either use something like updateAll:

ModelA.updateAll({_id: yourId}, data);

Or by using setId and then save:

var modelInstance = new ModelA(data);
modelInstance.setId(yourId);
modelInstance.save();

The reason why in your example it didn't update the data was that there was no id passed to the model constructor, you should either pass that or use setId.