[英]I am trying to fetch data in mongodb using node.js, but i can't get result
我已经编写了查询以从mongodb获取数据,但是我无法获得结果。 我的node.js文件如下所示
router.get('/manage-product', function(req, res){
console.log('I received get request');
var findProducts = function(db, callback) {
var cursor =db.collection('proInfo').find( ObjectId("56bc959942559b3847249b7e"));
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
console.dir(doc);
} else {
callback();
}
});
};
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
findProducts(db, function() {
db.close();
});
});
return res.json({
findProducts,
});
});
从这个节点,我无法将findProducts返回到我的控制器。 在萤火虫响应部分中,我只会得到这样的{}。 但是我在命令提示符下获取了值。
(function ()
{
'use strict';
angular
.module('app.manage-product')
.controller('ManageProductController', ManageProductController);
/** @ngInject */
ManageProductController.$inject = ['$http', '$scope'];
function ManageProductController($http, $scope)
{
var vm = this;
$http({
url: 'http://localhost:7200/api/manage-product',
method: 'GET',
//data: ''
}).success(function(res) {
console.log('success');
//$scope.productlist = res;
//vm.findProducts=res;
vm.findProducts=res.findProducts;
}, function(error) {
console.log(error);
alert('here');
});
console.log('i ma here');
}
})();
return res.json({
findProducts,
});
if (doc != null) { console.dir(doc); res.send(JSON.stringify(doc)); db.close(); } else { callback(); }
删除它并在您的node.js代码中更新它if (doc != null) { console.dir(doc); res.send(JSON.stringify(doc)); db.close(); } else { callback(); }
if (doc != null) { console.dir(doc); res.send(JSON.stringify(doc)); db.close(); } else { callback(); }
使用以下代码并尝试
router.get('/manage-product', function(req, res){
console.log('I received get request');
var findProducts = function(db, callback) {
var cursor =db.collection('proInfo').find( ObjectId("56bc959942559b3847249b7e")).toArray(function(err, docs){
if(err){
return callback(new Error("Some problem"));
}else{
return callback(null,docs);
}
});
};
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
findProducts(db, function(err,docs) {
db.close();
if(err) return res.json({result:null})
else
return res.json({result: docs });
});
});
});
在findProducts函数中尝试下面的代码
if (doc != null) {
console.dir(doc);
return doc;
}
您的最终回报应如下所示
return res.json(findProducts);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.