我将此代码另存为mongodb-connect.js
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/TodoApp', (err, db) => {
if(err){
return console.log('Unable to connect to mongo db server');
}
console.log('Connected to Mongo DB server');
db.collection('Todos').insertOne({
text: 'Something to do',
completed: false
}, (err, result) => {
if(err) {
return console.log('Unable to insert todo',err);
}
console.log(JSON.stringify(result.ops, undefined, 2));
});
db.close();
});
但显示如下:
(node:7720) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true
} to MongoClient.connect.
Connected to Mongo DB server
/home/ghoul/node-todo-api/node_modules/mongodb/lib/operations/mongo_client_ops.js:439
throw err; ^
TypeError: db.collection is not a function
at MongoClient.connect (/home/ghoul/node-todo-api/playground/mongodb-connect.js:9:8)
at result (/home/ghoul/node-todo-api/node_modules/mongodb/lib/utils.js:414:17)
at executeCallback (/home/ghoul/node-todo-api/node_modules/mongodb/lib/utils.js:40
6:9)
at err (/home/ghoul/node-todo-api/node_modules/mongodb/lib/operations/mongo_client_ops.js:285:5)
at connectCallback (/home/ghoul/node-todo-api/node_modules/mongodb/lib/operations/mongo_client_ops.js:240:5)
at process.nextTick (/home/ghoul/node-todo-api/node_modules/mongodb/lib/operations/mongo_client_ops.js:436:7)
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
答案 0 :(得分:2)
按照文档说明或使用以下方法将选项{ useNewUrlParser: true }
传递给connect方法:
cons url = 'your url';
const dbName = 'myproject';
MongoClient.connect(url, function(err, client) {
const db = client.db(dbName);
}