【问题标题】:MongoDb and Node.jsMongoDb 和 Node.js
【发布时间】:2021-11-28 23:21:48
【问题描述】:

所以我正在使用 node.js 和 mongodb,我是一个菜鸟 下面是我的代码:

const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/myproject';
MongoClient.connect(url,function(err,db){
 if (err){
     return console.dir(err);
 }
 console.log('connected to mdb');
 InsertDoc(db,function(){
  db.close(); 
 })
 });

 const InsertDoc= function(db, callback){

 const collection = db.collection('users');
 collection.insert({
     name : 'vishnu',
     email:'vishnu@123'
 },
 function(err,result){
     if(err){
         return console.dir(err);
     }
     console.log('inserted doc');
     console.log(result);
     callback(result);
 });
 }

 ERROR: TypeError: db.collection is not a function

我不确定我哪里出错了 请让我知道错误

【问题讨论】:

    标签: node.js mongodb typeerror


    【解决方案1】:

    connect 的回调将返回一个MongoClient 的实例和一个Db 的实例,正如官方Mongodb Node 驱动文档中所述,请看第二个示例

    https://mongodb.github.io/node-mongodb-native/4.1/classes/MongoClient.html

    获得集合后,您必须使用client.db(dbName) 获得db,这将为您提供用于创建collectiondb 对象。

    // Connect using the MongoClient.connect static method
    const MongoClient = require('mongodb').MongoClient;
    
    // Connection url
    const url = 'mongodb://localhost:27017/myproject';
    
    // Connect using MongoClient
    MongoClient.connect(url, function(err, client) {
      const db = client.db("myproject");
    
      const collection = db.collection("users");
      // do your thing
    
      client.close();
    });
    `
    

    【讨论】:

      猜你喜欢
      • 2016-09-29
      • 2013-02-24
      • 2014-03-20
      • 2013-12-30
      • 2014-12-12
      • 2013-08-19
      • 2016-02-03
      • 2012-08-18
      • 1970-01-01
      相关资源
      最近更新 更多