在链接到 Angular 控制器的服务器中使用 "Mongojs.ObjectID"
Using "Mongojs.ObjectID" in Server linked to Angular controller
我正在使用 MEAN 堆栈构建网络应用程序。我正在尝试根据控制器中的参数通过 ObjectId 过滤来自服务器的数据。我的参数适用于键值,例如按名称过滤,但按 ObjectID 过滤不起作用。我在 Mongojs.ObjectID.
中使用 MongoJS
Controller.js:
var refresh = function() {
$http.get('/collection', {params:{"_id":"111100000111"}}).success(function(response) {
console.log("Success");
$scope.collection = response;
});
};
refresh();
Server.js:
app.get('/collection', function(req,res){
if(req.query.id){
db.users.find({_id: mongojs.ObjectId(req.query.id)},function (err, docs) { console.log(docs); res.json(docs); });
}
else{
db.users.find(function (err, docs) { console.log(docs); res.json(docs); });
}
});
因为服务器端函数作为 if-else 运行,所以 "if" 在这种情况下失败,然后转到 "else",它会返回所有文档。我已经尝试了几乎所有在 "id" 和 adding/removing 引用 "id" 或“_id”之前添加“_”的组合。不同的组合带回了 "null",一个空数组,或者已经转到 "else" 语句。
您将 _id
作为查询参数传递。
这就是您的 GET 请求的样子:
/collection?_id=111100000111
但是您在 if
语句和 find
函数中查看 id
而不是 _id
。
所以它应该是这样的:
app.get('/collection', function(req,res) {
var _id = req.query._id;
if(_id) {
db.users.find({_id: mongojs.ObjectId(_id)},function (err, docs) { console.log(docs); res.json(docs); });
}
else {
db.users.find(function (err, docs) { console.log(docs); res.json(docs); });
}
});
我正在使用 MEAN 堆栈构建网络应用程序。我正在尝试根据控制器中的参数通过 ObjectId 过滤来自服务器的数据。我的参数适用于键值,例如按名称过滤,但按 ObjectID 过滤不起作用。我在 Mongojs.ObjectID.
中使用 MongoJSController.js:
var refresh = function() {
$http.get('/collection', {params:{"_id":"111100000111"}}).success(function(response) {
console.log("Success");
$scope.collection = response;
});
};
refresh();
Server.js:
app.get('/collection', function(req,res){
if(req.query.id){
db.users.find({_id: mongojs.ObjectId(req.query.id)},function (err, docs) { console.log(docs); res.json(docs); });
}
else{
db.users.find(function (err, docs) { console.log(docs); res.json(docs); });
}
});
因为服务器端函数作为 if-else 运行,所以 "if" 在这种情况下失败,然后转到 "else",它会返回所有文档。我已经尝试了几乎所有在 "id" 和 adding/removing 引用 "id" 或“_id”之前添加“_”的组合。不同的组合带回了 "null",一个空数组,或者已经转到 "else" 语句。
您将 _id
作为查询参数传递。
这就是您的 GET 请求的样子:
/collection?_id=111100000111
但是您在 if
语句和 find
函数中查看 id
而不是 _id
。
所以它应该是这样的:
app.get('/collection', function(req,res) {
var _id = req.query._id;
if(_id) {
db.users.find({_id: mongojs.ObjectId(_id)},function (err, docs) { console.log(docs); res.json(docs); });
}
else {
db.users.find(function (err, docs) { console.log(docs); res.json(docs); });
}
});