Node.js 使用SailsJS模型定义查询的getting属性
我想按id查询库,我只需要一些属性。我尝试了以下脚本,但它不起作用:Node.js 使用SailsJS模型定义查询的getting属性,node.js,mongodb,sails.js,Node.js,Mongodb,Sails.js,我想按id查询库,我只需要一些属性。我尝试了以下脚本,但它不起作用: 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); }); 我的代码有什么问题 对于投影,您
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);
});
我的代码有什么问题 对于投影,您可以使用直接访问mongo驱动程序的方法:
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);
});
});
-更新-
另一种选择是使用可以接受条件和投影文档作为参数并附加以仅返回一个文档的方法。对于投影对象,需要使用包含投影字段数组的选择键:
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 );
});
@非常感谢你的回答。我改变了一些东西,脚本运行良好
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);
});
});
不工作怎么办?除了一般认为sails/waterline查询期望的语法不同之外,最有可能的是在投影部分本身。尽管我定义了纬度、经度、名称、地址和图像中的5个属性,但数据仍然返回所有属性。