【发布时间】:2018-11-07 21:24:00
【问题描述】:
我有以下使用 MongoDb 的 Node.js 应用程序:
var MongoClient = require('mongodb').MongoClient;
var demoPerson = { name:'John', lastName:'Smyth' };
var findKey = { name: 'John' };
MongoClient.connect('mongodb://127.0.0.1:27017/demo', { useNewUrlParser: true }, function(err, client) {
const db = client.db('demo');
if(err) throw err;
console.log('Successfully connected');
//console.log(db);
var collection = db.collection('people');
collection.insert(demoPerson, function(err, docs) {
console.log('Inserted', docs[0]);
console.log('ID:', demoPerson._id);
collection.find(findKey).toArray(function(err, results) {
console.log('Found results:', results);
collection.remove(findKey, function(err, results) {
console.log('Deleted person');
db.close();
});
});
});
});
当我运行它时,我得到了这个错误:
TypeError: db.close is not a function
我不明白为什么这不起作用。有人可以帮忙吗?
【问题讨论】:
-
client.close()。前段时间在 API 中发生了变化,与client.db()同时发生了变化 -
是的,尼尔是对的。您应该使用从 MongoClient.connect 返回的
client,而不是db。 -
谢谢大家。这是一种享受。
标签: javascript node.js mongodb typeerror