Select specific fields from database
Asked Answered
J

4

14

I just want to know that is it possible to select specific fields using waterline, orientdb query is given below.

e.g. 
select phone from user

I want to select phone from user vertices by using this query

userModel.find(phone)
.then(function(phonelist){ 
  if(!phonelist) 
     console.log('msg: RECORD_NOT_FOUND'); 
  else 
     console.log(phonelist);
.catch(function(err){ console.log('err: 'err'); });
Jabalpur answered 21/4, 2015 at 9:50 Comment(0)
L
30

Yes, it's possible, you just need to add select to your search criteria, for example (assuming you are searching for a records with id 1):

userModel.find({ select: ['phone'], id: 1 })

or alternatively:

userModel.find({ select: ['phone'], where: { id: 1 } })

or if you want all records, you don't need to supply criteria:

userModel.find({ select: ['phone'] })

This doesn't seem to be documented anywhere but it should. In version 0.11 it will also possible to define select by doing model.pick('name', 'age'): https://github.com/balderdashy/waterline/pull/952

Lurlinelusa answered 21/4, 2015 at 10:46 Comment(5)
That does not work for me in Waterline 0.10.21, I get all the fields without any selection :( - I hope 0.11 is released soon!Falla
@FranDios, are you using sails-mongo? If so there was a bug in it that was only fixed and released 8 days ago (v0.11.3).Orientalism
Yes, I do use sails-mongo. Thanks for the info, will check it :)Falla
I've the same issue, updated sails-mongo to 0.11.3 but unfortunately the url: localhost:1337/modelName?select=['date'] still returns all the fields.Dacy
select works for me on sails v 0.12.13, however, how can i prevent id from tagging along with the response?Mazel
F
4

Source and more detail -https://mcmap.net/q/827415/-specify-returned-fields-in-node-js-waterline

Yes, it's possible but not with select as it's still in development. But there is a way to achieve it using fields.

Model.find({ id: id }, {
  fields: {
    name: 1,
    phoneNumber: 1
  }
}).limit(1).exec(function(...) {};

This won't work with findOne.

Fini answered 23/1, 2017 at 8:6 Comment(0)
G
4

In Sails version 1 they have added provision for sending query as well as projection to the find()/findOne() methods. You can simply do: Model.find({where: {id: id}, select: ['name', 'phoneNumber']})

Find reference here: https://sailsjs.com/documentation/reference/waterline-orm/models/find#?using-projection

Gentry answered 30/8, 2018 at 22:7 Comment(0)
L
2

You can use the .select() method

let phones = await userModel.find().select(['phone']);

The opposite of .select() is .omit()

Lody answered 9/8, 2019 at 17:24 Comment(2)
This is just for sails 1.0, right?Gaiser
@Gaiser yes, that's right.Lody

© 2022 - 2024 — McMap. All rights reserved.