Preston Lamb
Posted on May 31, 2019
Sails.js is one of my favorite Node frameworks. There are a lot of built in advantages that make getting up and running quick, easy, and painless. One of the benefits is the ORM/ODM that it comes with, Waterline. There are a lot of adapters that allow you to use many different databases with your application and no need to rewrite the database access code. This time, though, when using Waterline I got a little stuck, but here's how I got the data I wanted.
Let's say I have a model like this:
// MyModel
module.exports = {
attributes: {
field1: 'string',
field2: 'string',
field3: 'array'
}
}
and field3
is an array of objects. Now, I'm querying the database for results where one of the objects in field3
has an attribute that meets our criteria. From what I could tell, Waterline doesn't provide a way to do this out-of-the-box. But, it will allow you to use database-specific queries for complex scenarios. (I am more than happy to admit that I may have misunderstood this part. However, the query I'm about to show you does work. So at least I got the result I wanted!) Anyways, given the scenario above, here's a working query:
const results = await MyModel.find({ field3: { nestedAttr: searchParam } } );
This will give you objects that are in the array of field3
that have an attribute that match your searchParam
. This query works in Robomongo as well, which means it's more Mongo-specific than Waterline is normally. But in certain cases you (like me) may need to use the database-specific query.
Posted on May 31, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.