有人知道strongloop是否支持从MongoDB数据库查询返回的限制字段吗?我认为strongloop不支持所有MongoDB查询功能,所以我担心这可能不受支持。
这就是我想要使用strongloop:实现的目标
https://docs.mongodb.org/v3.0/tutorial/project-fields-from-query-results/
MongoDB操作示例(在数据库中执行):
不限制字段:
> db.Releases.find({epoch_time: {$gte: 1451417675, $lt: 1483717675}})
{ "_id" : ObjectId("5682bbcbab755688f9bfd939"), "release_id" : 3, "event_id" : 1, "epoch_time" : 1451417675 }
{ "_id" : ObjectId("5682bbccab755688f9bfd93a"), "release_id" : 4, "event_id" : 2, "epoch_time" : 1452717675 }
{ "_id" : ObjectId("5682bbccab755688f9bfd93b"), "release_id" : 5, "event_id" : 2, "epoch_time" : 1453717675 }
{ "_id" : ObjectId("5682bbccab755688f9bfd93c"), "release_id" : 6, "event_id" : 3, "epoch_time" : 1461207675 }
{ "_id" : ObjectId("5682bbccab755688f9bfd93d"), "release_id" : 7, "event_id" : 3, "epoch_time" : 1461407675 }
{ "_id" : ObjectId("5682bbccab755688f9bfd93e"), "release_id" : 8, "event_id" : 4, "epoch_time" : 1461417675 }
{ "_id" : ObjectId("5682bbccab755688f9bfd93f"), "release_id" : 9, "event_id" : 1, "epoch_time" : 1472717675 }
{ "_id" : ObjectId("5682bbd1ab755688f9bfd940"), "release_id" : 10, "event_id" : 5, "epoch_time" : 1473717675 }
限制字段:
> db.Releases.find({epoch_time: {$gte: 1451417675, $lt: 1483717675}},{_id:0,release_id:0,event_id:0})
{ "epoch_time" : 1451417675 }
{ "epoch_time" : 1452717675 }
{ "epoch_time" : 1453717675 }
{ "epoch_time" : 1461207675 }
{ "epoch_time" : 1461407675 }
{ "epoch_time" : 1461417675 }
{ "epoch_time" : 1472717675 }
{ "epoch_time" : 1473717675 }
我在StrongLoop中尝试了类似的操作,但我仍然得到了查询中的所有字段。
Release.find({where: {...query expression...} },
{_id:0,release_id:0,event_id:0}, //trying to limit return fields
function (err, releases) {
...
}
);
谢谢,Carlos
是的,loopbackjs支持限制查询中的字段。mongodb中限制文件和环回查询的区别在于,当使用字段过滤器时,环回js默认会将所有字段返回为false。您必须明确地说明您希望查询返回哪些字段。
Release.find({where: {release_id : 4}, fields: {epoch_time: true}}, //return only epoch_time
function (err, releases) {
...
}
);
字段过滤文档
根据strongloop文档-https://docs.strongloop.com/display/public/LB/Querying+数据
它提供了在REST端点和模型方法中添加查询、筛选和限制数据的多个选项的能力。
你可以用这样的远程方法限制输出中的字段-
Release.find(
{ fields : {"epoch_time":true}
}, function(err, releases) {
// ... your code here
} );
或者,您可以在中指定的操作挂钩中执行此操作https://docs.strongloop.com/display/public/LB/Operation+挂钩-
MyModel.observe('access', function logQuery(ctx, next) {
console.log('Accessing %s matching %s', ctx.Model.modelName, ctx.query.where);
next();
});
在我们的模型中创建一个函数
MyModel.observe('access', function logQuery(ctx, next) {
Release.find({
where: {
release_id: 4
}
});
});