[英]mongdb TypeError: db.collection is not a function
當我運行此代碼時,它有一個錯誤'TypeError:db.collection不是一個函數'。 如何解決此問題以及此代碼中的錯誤。
const MongoClient = require('mongodb').MongoClient; // Connection url const url = 'mongodb://localhost:27017/blog'; // Connect using MongoClient MongoClient.connect(url, (err, db) => { const note = { text: 'Note content text', title: 'Note title' }; db.collection('notes').insert(note, (err, result) => { if (err) { console.log('An error has occurred!') } else { console.log('Insert success!') } }); });
這是您在項目中安裝的mongodb版本錯誤。 您應該在項目中運行npm install mongodb@2.2.5 --save
對於MongoDB本機NodeJS驅動程序3.0版本的人員:
在MongoDB本機NodeJS驅動程序的2.x版中,您將獲取數據庫對象作為connect回調的參數:
MongoClient.connect('mongodb://localhost:27017/blog', (err, db) => {
// Database returned
});
根據3.0的changelog,您現在獲得一個包含數據庫對象的客戶端對象:
MongoClient.connect('mongodb://localhost:27017', (err, client) => {
// Client returned
var db = client.db('blog');
});
看看這個可能會幫助你更接近你需要的解決方案。
const url = 'mongodb://localhost:27017/learnyoumongo'
var mongo = require('mongodb').MongoClient
mongo.connect(url, function(err, client) {
if(err) {
throw err;
}
var collection = client.db('learnyoumongo').collection('parrots');
collection.find({
age : {
$gt : +process.argv[2]
}
}).toArray(function(err, documents) {
console.log(documents)
client.close()
})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.