0

I'm doing research on loopback and was wondering if it's possible to save to multiple models from one request. Say.. an Post has many Tags with many Images. A user form would have the following:

  • Post Title
  • Post Description
  • Tag Names (A multi field. E.g.: ['Sci-Fi', 'Fiction', 'BestSeller']
  • Image File (Hoping to process the file uploaded to AWS, maybe with skipper-s3?)

How would I be able to persist on multiple models like this? Is this something you do with a hook?

Handonam
  • 618
  • 8
  • 17

1 Answers1

3

You can create RemoteMethods in a Model, which can define parameters, so in your example you could create something like this in your Post model:

// remote method, defined below
Post.SaveFull = function(title, 
        description,
        tags,
        imageUrl,
        cb) {

    var models = Post.app.Models; // provides access to your other models, like 'Tags'

    Post.create({"title": title, "description": description}, function(createdPost) {
         foreach(tag in tags) {
             // do something with models.Tags

         }
         // do something with the image

         // callback at the end
         cb(null, {}); // whatever you want to return
    })

}

Post.remoteMethod(
    'SaveFull', 
    {
      accepts: [
          {arg: 'title', type: 'string'},
          {arg: 'description', type: 'string'},
          {arg: 'tags', type: 'object'},
          {arg: 'imageUrl', type: 'string'}
        ],
      returns: {arg: 'Post', type: 'object'}
    }
);
conradj
  • 2,481
  • 2
  • 24
  • 30
  • 1
    you're the best! I just noticed this as well as I was playing around with it, but this confirms it for me with great clarity. Thank you! – Handonam Dec 18 '15 at 16:53