gpt4 book ai didi

node.js - db.collection 不是一个函数

转载 作者:太空宇宙 更新时间:2023-11-03 22:41:10 25 4
gpt4 key购买 nike

我正在尝试使用 NodejsMongoDB 集合中简单地插入一个条目。这是我的代码:

代码:

const MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017/TodoApp', (err, db) => {
if (err) {
return console.log('Unable to connect to MongoDB server');
}
console.log('Connected to MongoDB server');

db.collection('Todos').insertOne({
text: 'Something to do',
completed: false
}, (err, result) => {
if (err) {
return console.log('Unable to insert todo', err);
}

console.log(JSON.stringify(result.ops, undefined, 2));
});

db.close();
});

当我运行代码时,它显示以下错误:

错误:

TypeError: db.collection is not a function

最佳答案

卸载现有的 mongodb 软件包并使用以下命令重新安装可以解决问题

npm uninstall mongodb --save
npm install mongodb@2.2.33 --save

版本 MongoDB >= 3 - 该数据库变量实际上是您尝试访问的对象的父对象。如果你使用 mongo 3+:

const myDb = db.db('YourDatabase') 
myDb.collection('YourDatabase).insertOne ....

关于node.js - db.collection 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47937018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com