简体   繁体   English

TypeError:db.collection不是MongoDB连接中的函数

[英]TypeError: db.collection is not a function in MongoDB Connection

I Have this Code saved as mongodb-connect.js 我将此代码另存为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();
});

but its showing: 但显示:

(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)

Pass option { useNewUrlParser: true } to the connect method as stated by documentation or use: 按照文档所述将选项{ useNewUrlParser: true }传递给connect方法,或使用:

cons url = 'your url';
const dbName = 'myproject';
MongoClient.connect(url, function(err, client) {
      const db = client.db(dbName);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM