[英]Search MongoDB using a variable sent from client
I'm using MongoJS in a Node project with Angular and trying to find documents based on a variable. 我在带有Angular的Node项目中使用MongoJS,并尝试基于变量查找文档。
server.js server.js
app.get('/api/find', function(req, res){
db.Fruits.find({code:'Apple'}).forEach(function(err, docs){
res.json(docs);
});
});
Route 路线
.when('/find/:fruit', {
templateUrl: 'views/find.html',
controller: 'findCtrl',
resolve: {
result: function(searchService) {
return searchService.getResult();
}
}
})
service.js (client) service.js (客户端)
.factory('searchService', function($q, $http) {
return {
getResult: function() {
return $http.get('/api/find')
.then(function(response) {
if (typeof response.data === 'object') {
return response.data;
} else {
return $q.reject(response.data);
}
})
}
}
})
Controller.js Controller.js
.controller('findCtrl', function($scope, result) {
$scope.result = result;
})
As you can see in server.js, I'm passing a static string 'Apple'. 如您在server.js中看到的,我正在传递静态字符串'Apple'。 I wanna replace that with the $routeparams ':fruit' which I've listed in Route. 我想用在Route中列出的$ routeparams':fruit'代替它。
Please help. 请帮忙。
You need to pass the url param :fruit to your searchService: 您需要将url param:fruit传递给searchService:
.when('/find/:fruit', {
templateUrl: 'views/find.html',
controller: 'findCtrl',
resolve: {
result: function(searchService) {
return searchService.getResult($route.current.params.fruit);
}
}
})
Search Service: 搜索服务:
.factory('searchService', function($q, $http) {
return {
getResult: function(fruit) {
return $http.get('/api/find?fruit=' + fruit)
.then(function(response) {
if (typeof response.data === 'object') {
return response.data;
} else {
return $q.reject(response.data);
}
})
}
}
})
Server: I normally use mongoose but you could probably use .toArray as using forEach was iterating over the collection and attempting to end the response multiple times. 服务器:我通常使用猫鼬,但您可能可以使用.toArray,因为使用forEach遍历集合并尝试多次终止响应。
app.get('/api/find', function(req, res){
db.Fruits.find({code:req.query.fruit}).toArray(function (err, result) {
return res.json(result);
});
});
EDIT: Just read that you're using mongojs You should be able to do: 编辑:只需阅读您正在使用mongojs,您应该能够:
app.get('/api/find', function(req, res){
db.Fruits.find({code:req.query.fruit}, function (err, docs) {
return res.json(docs);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.