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?
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 );
});
@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);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With