鍍金池/ 問答/數(shù)據(jù)庫  HTML/ 采用node.js連接MongoDB數(shù)據(jù)成功之后,拋出錯誤,db.collect

采用node.js連接MongoDB數(shù)據(jù)成功之后,拋出錯誤,db.collection不是一個函數(shù)。

采用node.js連接MongoDB數(shù)據(jù)成功之后,想在數(shù)據(jù)庫中寫入數(shù)據(jù),卻顯示db.collection不是一個函數(shù)。app.js代碼如下圖所示:

clipboard.png
cmd拋出的錯誤提示如下圖所示:

clipboard.png

求各位大神指導(dǎo)!

回答
編輯回答
涼薄

不用回退版本,本人親測高版本連接操作數(shù)據(jù)庫 代碼如下

// 3.0 以上 高版本語法

const express = require('express');
const router = express.Router();
const mongoClient = require('mongodb').MongoClient;
const assert = require('assert');
mongoClient.connect("數(shù)據(jù)庫地址", function(err, client) { assert.equal(null, err);

// admin 為 數(shù)據(jù)庫名稱;
const db = client.db("admin");
// PASS 為 數(shù)據(jù)庫里面的某一個集合;
const pass = db.collection('PASS');

pass.find({}).toArray(function(err, docs) {

assert.equal(err, null);

console.log(docs);

});

});

module.exports = router;

2018年5月9日 01:54
編輯回答
慢半拍

在nodejs里的寫法和命令行中的寫法不一樣。

可以參考這篇文章,前面關(guān)于express框架的可以忽略,重點看數(shù)據(jù)庫連接和操作部分
點擊這里
具體操作文檔可以參考官方社區(qū)的API
mongodb官方文檔
完整項目可以參考這個項目的實現(xiàn)
基于 node.js + Mongodb 構(gòu)建的后臺系統(tǒng)

2017年6月22日 01:32
編輯回答
使勁操

這個錯誤是出在mongodb的庫中,只需要把node_modules中mongodb的版本換為2.3.33vision即可解決;

"dependencies": {
"mongodb": "^2.2.33"}

然后:

npm install
2017年1月28日 14:58