1、错误描述
Administrator@USER-0GUONPPBHK MINGW64 /f/dojo/abcd/abcc/public/javascripts
$ node mongodb.js
F:\dojo\abcd\abcc\node_modules\mongodb\lib\utils.js:429
throw new TypeError('final argument to `executeOperation` must be a callback');
^
TypeError: final argument to `executeOperation` must be a callback
at executeOperation (F:\dojo\abcd\abcc\node_modules\mongodb\lib\utils.js:429:11)
at MongoClient.connect (F:\dojo\abcd\abcc\node_modules\mongodb\lib\mongo_client.js:168:10)
at Object.<anonymous> (F:\dojo\abcd\abcc\public\javascripts\mongodb.js:8:8)
at Module._compile (internal/modules/cjs/loader.js:721:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)
at Module.load (internal/modules/cjs/loader.js:620:32)
at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
at Function.Module._load (internal/modules/cjs/loader.js:552:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:774:12)
at executeUserCode (internal/bootstrap/node.js:499:15)
2、错误原因
添加了useNewUrlParser:true属性,需要一个回调函数
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const DB_URL = 'mongodb://localhost:27017/';
const DB_NAME = 'student';
const client = new MongoClient(DB_URL);
//查询数据
client.connect({useNewUrlParser:true},function(err){
if(err) throw err;
assert.equal(null,err);
const db = client.db(DB_NAME);
client.close();
});
3、解决办法
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const DB_URL = 'mongodb://localhost:27017/';
const DB_NAME = 'student';
const client = new MongoClient(DB_URL);
//查询数据
MongoClient.connect(DB_URL+DB_NAME,{useNewUrlParser:true},function(err,db){
if(err) throw err;
client.collection(DB_NAME),find({}).toArray(function(err,result){
if(err) throw err;
console.log(result);
callback(result);
db.close();
});
});