我正在使用Loopback创建Rest API。需要根据集合中的特定列获取不同的数据。我在下面尝试过,但它不起作用,相反,下面的代码片段也在获取重复数据:
this.app.models.location.find(
{
distinct: ("regionName",
{state: st})
}
,
function(err, location){........}
'RegionName‘是' location’集合的属性,我只需要由'st‘表示的选定状态的数据(state是location集合的另一个属性)。谢谢。
发布于 2016-10-20 00:24:45
我在下面两个例子中得到了答案:
1.)没有查询,只是在"Role“集合的"name”字段上有distinct:
var roleCollection = user.app.models.Role.getDataSource().connector.collection(user.app.models.Role.modelName);
roleCollection.distinct( "name",
function(err, records) {
if(err) {
return cb(err);
} else {
return cb(null, records);
}
});
2.)通过查询,distinct在" role“集合的" name”字段中删除任何名称为“admin”的角色:
var roleCollection = user.app.models.Role.getDataSource().connector.collection(user.app.models.Role.modelName);
roleCollection.distinct( "name", { name: { $ne: 'admin' } },
function(err, records) {
if(err) {
return cb(err);
} else {
return cb(null, records);
}
});
Loopback.io v2.29.1
发布于 2016-02-28 16:28:13
我现在已经在我的项目中工作了。
这里有一些示例代码(用来帮助解释你的问题),它们应该能做你需要的事情……
// Distinct regions
Locations.regions = function (cb) {
console.log('Locations.build');
var ds = Locations.app.datasources.myDS;
var sql = "SELECT DISTINCT region FROM Locations ORDER BY region"; // here you write your sql query.
ds.connector.execute(sql, [], function (err, regions) {
if (err) {
cb(err, null);
} else {
cb(null, regions);
}
});
};
Locations.remoteMethod(
'regions', {
http: {
path: '/regions',
verb: 'get'
},
returns: {
root: true,
type: 'object'
}
}
);
**注意:这是针对MySQL的,但您应该能够修改其他连接器的查询**
发布于 2015-10-21 19:13:49
Loopback框架还没有提供独特的功能。
使用distinct的Mongo数据库查询如下:
db.runCommand ( { distinct: "<collection>", key: "<field>", query: { <query>} })
请参阅以下链接:
https://stackoverflow.com/questions/33229757
复制相似问题