没有条件且提供 fields/select 的 WaterlineJs find() 不起作用
WaterlineJs find() with no criteria and fields/select provided does not work
我正在尝试获取所有记录,但使用选定的字段,我尝试了以下方法,但 none 有效:
Post.find(
{
where: {},
select: ['title']
}
);
Post.find(
{},
{
fields: {
title: 1
}
}
);
正如 this 答案指出的那样,字段参数 "WILL work as long as you pass other params with it such as limit
or order
."
或者,如果您希望在整个应用程序中都这样做,您可以在 attributes
下为您的模型定义自定义 toJSON
函数。如果不是,您仍然可以在其他一些(例如 filter
)下定义它,并使用 map
到 return 自定义对象而不是默认模型。不过,请记住在使用 map
时注意控制流。在处理所有对象之前使用 async/promises/raw 逻辑来避免 returning。
我试过试图获得上述答案以使用限制或命令踢入投影但无济于事。
我确实在位于此处的文档中看到了这一点:
http://sailsjs.org/documentation/reference/waterline-orm/models/native
开箱即用的解决方案正是您正在做的事情(粘贴在这里以便于使用)。
Pet.native(function(err, collection) {
if (err) return res.serverError(err);
collection.find({}, {
name: true
}).toArray(function (err, results) {
if (err) return res.serverError(err);
return res.ok(results);
});
});
换掉响应基础的东西并将 Pet 更改为 Post,这应该可以在 sails 控制台中工作:
Post.native(function(err, collection) {
if (err) throw new Error(err);
collection.find({}, {
title: true
}).toArray(function (err, results) {
if (err) throw new Error(err);
console.log(results);
});
});
您仍然会得到 _id 字段,如果您不想要它,请点击 Mongo 文档,了解没有得到那些 hint(title: true , _id: false)提示
希望对您有所帮助!
问题已在 sails-mongo 最新版本中解决:
https://github.com/balderdashy/waterline/issues/1098
谢谢
我正在尝试获取所有记录,但使用选定的字段,我尝试了以下方法,但 none 有效:
Post.find(
{
where: {},
select: ['title']
}
);
Post.find(
{},
{
fields: {
title: 1
}
}
);
正如 this 答案指出的那样,字段参数 "WILL work as long as you pass other params with it such as limit
or order
."
或者,如果您希望在整个应用程序中都这样做,您可以在 attributes
下为您的模型定义自定义 toJSON
函数。如果不是,您仍然可以在其他一些(例如 filter
)下定义它,并使用 map
到 return 自定义对象而不是默认模型。不过,请记住在使用 map
时注意控制流。在处理所有对象之前使用 async/promises/raw 逻辑来避免 returning。
我试过试图获得上述答案以使用限制或命令踢入投影但无济于事。
我确实在位于此处的文档中看到了这一点: http://sailsjs.org/documentation/reference/waterline-orm/models/native
开箱即用的解决方案正是您正在做的事情(粘贴在这里以便于使用)。
Pet.native(function(err, collection) {
if (err) return res.serverError(err);
collection.find({}, {
name: true
}).toArray(function (err, results) {
if (err) return res.serverError(err);
return res.ok(results);
});
});
换掉响应基础的东西并将 Pet 更改为 Post,这应该可以在 sails 控制台中工作:
Post.native(function(err, collection) {
if (err) throw new Error(err);
collection.find({}, {
title: true
}).toArray(function (err, results) {
if (err) throw new Error(err);
console.log(results);
});
});
您仍然会得到 _id 字段,如果您不想要它,请点击 Mongo 文档,了解没有得到那些 hint(title: true , _id: false)提示
希望对您有所帮助!
问题已在 sails-mongo 最新版本中解决:
https://github.com/balderdashy/waterline/issues/1098
谢谢