1
// many-to-many association
// Adding pet.id:20 into user
user.pets.add(20);
user.save(function(err,s){
 // Inefficient
 Pet.findOne(20).exec(function(err, pet){
 })
});

Is there a way to refer to the pet that I have just added the association to? It's inefficient to do a pointless query, because s returns the object that has just been saved. it would be useful if there is a way to reference the pet by doing something like s.pets(whatever).

holyxiaoxin
  • 690
  • 1
  • 7
  • 26

1 Answers1

1

There's not really a way to get around making the query every time because when the the model is being updated, the server doesn't load the other model (i.e relation) in memory to do that.

What you could try, to save yourself from having to do that each time is to override either the toJSON (ref.) of a particular collection or override the update blueprint action to override for all collections. But overall it might not be a bad idea to fetch it as and when you'd require it.

Community
  • 1
  • 1
r0hitsharma
  • 1,592
  • 12
  • 16
  • It seems that I cannot refer to the model's association even after saving it. It's quite different from Rails. That's the bane of using Sails I guess. But async queries are definitely much faster and I probably shouldn't be too bothered by them. – holyxiaoxin Jan 29 '15 at 14:37
  • 1
    Yes, since a relation is another model, you'd need to load it either by loading the previous model and doing a populate or using the reference provided in the relation (database id hash) to load the related model. I haven't used rails so can't say if there's a correlation. – r0hitsharma Feb 02 '15 at 10:51