Mongodb讀寫(xiě)數(shù)據(jù)錯(cuò)誤: db.collection is not a function

Node調(diào)用mongodb寫(xiě)如數(shù)據(jù)異常

最近有看學(xué)習(xí)使用Express,然后按照網(wǎng)上一些教程編寫(xiě)demo,但是發(fā)現(xiàn)在結(jié)合mongodb使用時(shí),總會(huì)報(bào)錯(cuò);最后搜索一番,原來(lái)是mongodb的版本3.x2.x寫(xiě)法不同,所以才會(huì)提示報(bào)錯(cuò)。

我的版本: "mongodb": "^3.5.7"

如果使用2.x版本,網(wǎng)友說(shuō)可以將版本降至: "mongodb": "^2.2.33"

問(wèn)題描述

使用nodejs,連接mongodb,數(shù)據(jù)寫(xiě)入提示異常:

TypeError: db.collection is not a function
或
TypeError: db.open is not a function
或
TypeError: db.close is not a function
或
TyepError: client.insert is not a function

錯(cuò)誤方式

以下是按照博主的demo寫(xiě)的,就提示TypeError: db.open is not a function

  //打開(kāi)數(shù)據(jù)庫(kù)
  mongodb.open(function (err, db) {
    if (err) {
      return callback(err);//錯(cuò)誤,返回 err 信息
    }
    //讀取 users 集合
    db.collection('users', function (err, collection) {
      if (err) {
        mongodb.close();
        return callback(err);//錯(cuò)誤,返回 err 信息
      }
      //查找用戶名(name鍵)值為 name 一個(gè)文檔
      collection.findOne({
        name: name
      }, function (err, user) {
        mongodb.close();
        if (err) {
          return callback(err);//失??!返回 err 信息
        }
        callback(null, user);//成功!返回查詢的用戶信息
      });
    });
  });

正確方式

var MongodbClient = require('mongodb').MongoClient
var url = 'mongodb://localhost:27017/blog'

// 連接數(shù)據(jù)庫(kù)
MongodbClient.connect(url, function(err, client) {
  if (err) {
    return callback && callback(err)
  }
  
  var db = client.db('blog')
  db.collection('users').findOne({ username: username }, function(err, result) {
    client.close()
    if (err) {
      return callback && callback(err)
    }
    callback(null, result)
  })
})

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容