Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define getting property on query using SailsJS model

I want to query a library by id, and I need only some properties. I tried below script but it is not working:

Library.findOne({
  id: libraryId
}, {
  latitude: 1, longitude: 1,
  name: 1, address: 1, image: 1
}).exec(function (err, libObj) {
  if (err)
    return res.ok(err);

  return res.ok(libObj);
});

What is wrong in my code?

like image 751
Thanh Dao Avatar asked Aug 03 '26 21:08

Thanh Dao


2 Answers

For projections you could use the native() method that has direct access to the mongo driver:

var criteria = { id: libraryId },
    projection = { latitude: 1, longitude: 1, name: 1, address: 1, image: 1 };
// Grab an instance of the mongo-driver
Library.native(function(err, collection) {        
    if (err) return res.serverError(err);

    // Execute any query that works with the mongo js driver
    collection.findOne(criteria, projection).exec(function (err, libObj) {
        console.log(libObj);
    });
});

-- UPDATE --

Another option is to use the find() method which can accept the criteria and projection documents as parameters and append limit(1) to return just one document. For the projection object you would need to use the select key that holds an array of the projection fields:

var criteria = { _id: Library.mongo.objectId(libraryId) },
    projection = { select: [ "latitude", "longitude", "name", "address", "image" ] };

Library.find(criteria, projection).limit(1).exec(function (err, res) {
    var libObj = res[0];
    console.log(libObj );
});
like image 108
chridam Avatar answered Aug 06 '26 14:08

chridam


@chridam Thanks a lot for your answer. I changed something and the script working well

var criteria = { _id: Library.mongo.objectId(libraryId) },
    projection = { latitude: 1, longitude: 1, name: 1, address: 1, image: 1 };

// Grab an instance of the mongo-driver
Library.native(function(err, collection) {        
    if (err) return res.serverError(err);

    // Execute any query that works with the mongo js driver
    collection.findOne(criteria, projection, function (err, libObj) {
        sails.log(libObj);
        sails.log(err);
    });
});
like image 41
Thanh Dao Avatar answered Aug 06 '26 13:08

Thanh Dao