Waterline ORM (sails.js) conditions with NOT Equal in query
Asked Answered
B

3

12

How can I write a NOT Equal condition in Waterline?

This code:

Users
  .count()
  .where({
     id: { '!=': req.params.id},
     lastname: req.body.lastname
  })

Does nothing... (disk adapter in sails.js)

Borkowski answered 4/12, 2013 at 15:13 Comment(0)
D
17

First thing, it do nothing because looking into database is asynchronous. You have to make the chain longer and add exec or something from Q library like then.

User.count().where({
    id: { '!=': req.params.id },
    lastname: req.body.lastname
}).exec(function(err, num){
    console.log(num);
});

Now it returns 0. To make it return proper number instead of '!=' just write '!'.

Dreddy answered 5/12, 2013 at 13:14 Comment(0)
H
12

Adding this answer for anyone using Postgres. I was trying this and banging my head against a wall as it wasn't working and I couldn't figure out why. I searched all over and kept finding this answer.

If you are on postgres you want to use

id: { not: req.params.id }

After looking through Sailsjs docs and searching google long and hard I found this answer in the comments of the sails-postgresql module query.js. Hopefully this helps save someone in the same situation some time. Here is the full comment block that saved my sanity.

/**
 * Specifiy a `where` condition
 *
 * `Where` conditions may use key/value model attributes for simple query
 * look ups as well as more complex conditions.
 *
 * The following conditions are supported along with simple criteria:
 *
 *   Conditions:
 *     [And, Or, Like, Not]
 *
 *   Criteria Operators:
 *     [<, <=, >, >=, !]
 *
 *   Criteria Helpers:
 *     [lessThan, lessThanOrEqual, greaterThan, greaterThanOrEqual, not, like, contains, startsWith, endsWith]
 *
 * ####Example
 *
 *   where: {
 *     name: 'foo',
 *     age: {
 *       '>': 25
 *     },
 *     like: {
 *       name: '%foo%'
 *     },
 *     or: [
 *       { like: { foo: '%foo%' } },
 *       { like: { bar: '%bar%' } }
 *     ],
 *     name: [ 'foo', 'bar;, 'baz' ],
 *     age: {
 *       not: 40
 *     }
 *   }
 */
Horseweed answered 24/3, 2014 at 3:26 Comment(0)
P
0

I haven't used count directly, I have used length to know count.

let user = User.find({
   where: {
    id: { '!=': req.params.id },
    lastname: req.body.lastname
  }
});
let count = user.length;
Payroll answered 26/1, 2021 at 11:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.