【发布时间】:2014-11-24 14:17:31
【问题描述】:
我正在尝试仅查找与我的 id 参数匹配的商店。在终端一切看起来都很好:
GET /admin/company?_id=5470e913d20b3dab7c13218b 200 219.590 ms - -
然后这是我的 $resource
angular.module('mean.management').factory('Companies', ['$resource',
function($resource) {
return $resource('/admin/company/:companyId', {
companyId: '@_id'
}, {
update: {
method: 'PUT'
},
get: {method: 'GET',isArray: true}
});
}
]);
它使用正确的 _id 进行搜索,但它返回的是一堆公司的列表,而不仅仅是一个公司。
这是控制器
$scope.newStore = function () {
Companies.get({
_id: $scope.global.user.company // _id works fine
}, function (company2) {
console.log(company2); // this logs 40 different companies when it should be one matching the _id
});
};
如果我将 Companies.get 替换为 Companies.query,则会出现同样的问题。不会改变任何东西。我还更改了 get: {method: 'GET', isArray: false} 而不是 true,这只会在浏览器控制台中返回错误(因为它是一个数组)。
更新:我知道参数是正确的,因为如果我转到 localhost:3000/admin/company?_id=5470e913d20b3dab7c13218b 和 ctrl+f 5470e913d20b3dab7c13218b 我可以看到其中包含该 _id 的对象。
Update2:我想我离解决方案越来越近了。如果我注释掉它,它不会返回任何文章
// routes
app.get('/admin/company', companies.all); // if I comment this, it won't return anything
app.get('/admin/company/:companyId', companies.oneCompany); // this doesn't seem to be doing anything
更新3 下面是一些服务器端代码示例
exports.oneCompany = function(req, res, next, id) {
Company.load(id, function(err, article) {
if (err) return next(err);
if (!article) return next(new Error('Failed to load article ' + id));
req.article = article;
res.json(req.article);
next();
});
};
这是我试过的另一个
exports.company1 = function (req, res, next, id) {
Company
.findOne({
_id: id
})
.exec(function (err, user) {
if (err) return next(err);
if (!user) return next(new Error('Failed to load User ' + id));
req.profile = user;
res.json(user);
next();
});
};
【问题讨论】:
-
您应该知道返回结果的不是 $resource,而是服务器。因此,您应该对服务器端发生的事情有所了解。您有权访问服务器代码吗?
-
刚刚添加了两个我试过的服务器端示例,但没有成功。
-
想通了...不知道怎么做。当我简化代码/变量名称时,我将在下面编写一个解决方案。