使用express连接数据库操作
var express = require('express');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var MGurl = "mongodb://localhost:27017/";
app.get('/search',function(req,res){
res.header("Content-Type", "application/json;charset=utf-8");
MongoClient.connect(MGurl,{useNewUrlParser:true},function(err,db){
if(err){
console.log('数据库连接失败');
console.log(err);
return;
}else {
var mydb = db.db('itying');
var arr = [];
var mydbData = mydb.collection('user').find();
mydbData.each(function(err,doc){
console.log(doc)
if(err){
console.log(err);
}else {
if(doc!=null){
arr.push(doc);
}else {
console.log(arr);
}
}
})
//数据库读取是异步操作
setTimeout(function(){
res.send(arr)
},100)
}
})
})