node.js - 使用 SailsJS 模型定义查询属性

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

我的代码有什么问题吗?

最佳答案

对于预测,您可以使用 native() 可以直接访问 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);
    });
});

-- 更新 --

另一个选项是使用 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 );
});

关于node.js - 使用 SailsJS 模型定义查询属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32966691/

相关文章:

node.js - 如何删除列表的内容而不仅仅是列表?如果x在y中,则删除x时也删除y

java - 如何在spring-boot程序中根据条件访问mongoDB中的子文档

sails.js - 如何开始使用套接字机器包?

php - 从 php 启动 Node 似乎可以让 php 保持运行?

node.js - 参数前置条件中的命名路由

python - mongodb游标id无效错误

sails.js - 在 Sails.js 中动态创建模型

node.js - 将变量从 NodeJS 运行时传递回 CloudFormation

node.js - 忽略 Cloud Functions 中已完成函数的异常

node.js - 如何在 sails.js 中跟踪退回的电子邮件或未送达的电子邮件