Tuesday, November 10, 2020

Sails Working with queries

Queries (aka query instances) are the chainable deferred objects returned from model methods like .find() and .create(). They represent a not-quite-yet-fulfilled intent to fetch or modify records from the database.

The purpose of query instances is to provide a convenient, chainable syntax for working with your models. Methods like .populate(), .where(), and .sort() allow you to refine database calls before they're sent down the wire. Then, when you're ready to fire the query off to the database, you can just await it.

If you are using an older version of Node.js that does not support JavaScript's await keyword, you can use .exec() or .then()+.catch(). See the section on "Promises and Callbacks" below for more information.

When you execute a query using await, a lot happens.

await query;

First, the query is "shaken out" by Waterline core into a normalized query. Then it passes through the relevant Waterline adapter(s) for translation to the raw query syntax of your database(s) (e.g. Redis or Mongo commands, various SQL dialects, etc.) Next, each involved adapter uses its native Node.js database driver to send the query out over the network to the corresponding physical database.

When the adapter receives a response, it is marshalled to the Waterline interface spec and passed back up to Waterine core, where it is integrated with any other raw adapter responses into a coherent result set. At that point, it undergoes one last normalization before being passed back to "userland" (i.e. your code) for consumption by your app.


Error handling

You can use a try/catch to handle specific errors, if desired:


var zookeepersAtThisZoo;

try {

  zookeepersAtThisZoo = await Zookeeper.find({

    zoo: req.param('zoo')

  }).limit(30);

} catch (err) {

  switch (err.name) {

    case 'UsageError': return res.badRequest(err);

    default: throw err;

  }

}


return res.json(zookeepersAtThisZoo);



.fetch()


Tell Waterline (and the underlying database adapter) to send back records that were updated/destroyed/created when performing an .update(), .create(), .createEach() or .destroy() query. Otherwise, no data will be returned (or if you are using callbacks, the second argument to the .exec() callback will be undefined).


Warning: This is not recommended for update/destroy queries that affect large numbers of records.


var newUser = await User.create({ fullName: 'Alice McBailey' }).fetch();

sails.log(`Hi, ${newUser.fullName}!  Your id is ${newUser.id}.`);


.where(whereClause)


To find all the users named Finn whose email addresses start with 'f':


var users = await User.find({ name: 'Finn' })

.where({ 'emailAddress' : { startsWith : 'f' } });

return res.json(users);


references:

https://sailsjs.com/documentation/reference/waterline-orm/queries




No comments:

Post a Comment