试图在expressjs中获取mongodb的数组结果

时间:2019-03-05 14:39:45

标签: javascript node.js mongodb express mongoose

我正在尝试从MongoDB数据库返回一个结果,作为对GET请求的响应,当我进行调用时,响应中未定义,我可以在数据库的控制台日志中看到结果代码的一面。我感觉它可能与数组有关

MongoClient = require('mongodb'),
  mongodburl = "mongodb://localhost:27017",
  mongo = require('mongodb'),
  assert = require('assert');


let method={}
method.insertdata=function(data,collectionpara) {
  MongoClient.connect(mongodburl, function (err, db) {
    assert.equal(null, err);
    let dbo = db.db("hor-usData");
    let myobj = data;
    dbo.collection(collectionpara).insert(myobj, function (err, result) {
      assert.equal(null, err);
      console.log("insert data");
      db.close();
    })
  })
}

method.deleteRecords=function(collectionpara) {
  MongoClient.connect(mongodburl, function (err, db) {
    assert.equal(null, err);
    let dbo = db.db("hor-usData");
    var myquery = {
      title: /^B/
    };
    dbo.collection(collectionpara).deleteMany(myquery, function (err, obj) {
      if (err) throw err;
      console.log(obj.result.n + " document(s) deleted");
      db.close();
    })
  })
}
method.getdata=function(collectionpara){
  MongoClient.connect(mongodburl, function(err, db) {
    if (err) throw err;
    let dbo = db.db("hor-usData");
    dbo.collection(collectionpara).find().toArray(function(err, result) {
      if (err){
        return reject(err)
      }
      console.log('result',result);
      return resolve(result);
    });
  });  
}

module.exports = method;

和我的路由器代码

let assert = require('assert'),
    express = require('express'),
    router = express(),
    swaggerUi = require('swagger-ui-express'),
    database=require('../databaseCon'),
   // swaggerDocument = require('./swagger.json'),
    utils = require('../utils/utils');
var port = process.env.PORT || 3000;


//get donedeal
router.get('/getDonedeal', function (req, res, next) {
    let donedealResult = []
    donedealResult=database.getdata('donedeal');
    res.send(donedealResult);
});

//get carzone
router.get('/getCarzone', function (req, res, next) {
    let carzoneResult = [];
    carzoneResult=database.getdata('carzone');
    res.send(console.log(carzoneResult));
});


router.get('/cars', function (req, res, next) {
    res.router('Mainrouter')
});

router.get('/getCarzone', function (req, res, next) {
    var resultArray = []
});
router.listen(port);
//app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
//app.use('/api/v1', router);
module.exports = router;

0 个答案:

没有答案