6499

Sails.js/waterline: Executing waterline queries in toJSON function of a model?

I have the following model, let's say it describes a book:

module.exports = { attributes: { name: { type: 'String', required: true }, type: { type: 'string', required: true }, book_id: { type: 'integer' } } }

Here the 'type' attribute is the genre of the book, for example HorrorBook. I have a separate model for HorrorBooks, FantasyBooks and such, since the structure of the models differs from each other so much, they have fields the other doesn't have etc, which is why I can't just use a single generic Book-model. HorrorBook, FantasyBook etc each have their own 'id' fields, meaning there can be both a HorrorBook and a FantasyBook with the same id. When creating the book, I have a beforeCreate function that also creates an entry in HorrorBook or FantasyBook depending on the 'type' attribute of the book.

What I'm trying to do is that on queries on Book from the frontend, I'd like to include the relevant information of the book in an 'information' attribute, which is for example a HorrorBook entry.

toJSON: function() { var obj = this.toObject(); switch (obj.type) { case 'HorrorBook': HorrorBook.find({id: obj.book_id}) .exec(function(err, book_info) { obj.book_info = book_info; return obj; }) } }

However, this leads to the toJSON just returning null all the way. What I'm assuming is that the query being asynchronous makes it too slow or something, so it doesn't make it to the 'return' call at all. So what should I do about this? Is there a way to succeed in what I'm trying, or should I change my approach somehow?

Answer1:

What I'm assuming is that the query being asynchronous makes it too slow or something, so it doesn't make it to the 'return' call at all.

What's happening is that toJSON() is sync'ed and it's returning whatever comes out of HorrorBook.find({id: obj.book_id}).exec(), undefined sounds about right.

If you need to run something async your best bet is to create an async toJSON() instance method, for example (not tested):

toJSONAsync: function(callback) { var obj = this.toObject(); switch (obj.type) { case 'HorrorBook': HorrorBook.find({id: obj.book_id}) .exec(function(err, book_info) { obj.book_info = book_info; callback (obj); }) } }

And now you can get your result by doing:

book.toJSONAsync(function(json){ console.log(json); })

Recommend

  • Print in single Pthread
  • Using an R Markdown Document as a source for functions
  • Memory usage differs greatly (and strangely) between frontend and backend
  • iText as text Extracting/Reading from PDF on android
  • Which table should be Parent table and which should be child table?
  • Capturing STDOUT in RSpec
  • ASP.NET MVC2 Error: No parameterless constructor defined for this object
  • Is WITH the replacement for a #TEMP table?
  • Can I use Jquery to automatically find and set the width and height of a variety of images?
  • Can a Collections.shuffle be considered equivalent to a series of Randoms?
  • custom string delimiters stringtemplate-4
  • How to open multiple instances of a program in Linux
  • EntLib Way to Bind “Null” Value to Parameter
  • is there a way to update filter with async data
  • Django return user model id with L
  • Django model for a Postgres view
  • Trying to string.Join an IList
  • Set focus to first invalid form element in AngularJS
  • Find group of records that match multiple values
  • Combining two different ActiveRecord collections into one
  • How to assign byte[] as a pointer in C#
  • Moving Android View and preventing onDraw to be called over and over again
  • Remove final comma from string in vb.net
  • Rails Find when some params will be blank
  • How to do unit test for HttpContext.Current.Server.MapPath
  • Initializer list vs. initialization method
  • Control modification in presentation layer
  • How can I send an e-mail from a vbs script
  • Fetching methods from BroadcastReceiver to update UI
  • Can Jackson SerializationFeature be overridden per field or class?
  • Javascript convert timezone issue
  • Redux, normalised entities and lodash merge
  • Do create extension work in single-user mode in postgres?
  • Apache 2.4 - remove | delete | uninstall
  • How to delete a row from a dynamic generate table using jquery?
  • json Serialization in asp
  • KeystoneJS: Relationships in Admin UI not updating
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • how does django model after text[] in postgresql [duplicate]
  • How to stop GridView from loading again when I press back button?