【问题标题】:Define getting property on query using SailsJS model使用 SailsJS 模型在查询中定义获取属性
【发布时间】:2015-10-06 18:24:08
【问题描述】:

我想通过 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);
});

我的代码有什么问题?

【问题讨论】:

  • 不工作怎么办?除了普遍怀疑“帆/水线”查询期望是针对不同的语法,而且很可能在“投影”部分本身。
  • 数据仍然返回所有属性,尽管我定义了其中的 5 个(纬度、经度、名称、地址、图像)。

标签: node.js mongodb sails.js


【解决方案1】:

对于投影,您可以使用直接访问 mongo 驱动程序的 native() 方法:

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);
    });
});

-- 更新--

另一种选择是使用 find() 方法,该方法可以接受标准和投影文档作为参数并附加 limit(1) 以仅返回一个文档。对于投影对象,您需要使用包含投影字段数组的 select 键:

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 );
});

【讨论】:

    【解决方案2】:

    @chridam 非常感谢您的回答。我改变了一些东西,脚本运行良好

    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);
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-15
      • 1970-01-01
      • 2016-01-23
      相关资源
      最近更新 更多