DEV Community

Preston Lamb
Preston Lamb

Posted on • Originally published at on

Finding an Object in an Array with Waterline

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'
Enter fullscreen mode Exit fullscreen mode

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 } } );
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)