[英]MongoDB Node.js TypeError: Cannot read property 'db' of null
I'm making a DB for my project, but in this code:我正在为我的项目创建一个数据库,但在这段代码中:
function getallvideos(callback) {
MongoClient.connect(url, function(err, client) {
const db = client.db("cathub")
db.collection("videos", function(err, collection) {
collection.find().toArray(function(err, res) {
callback(res)
})
})
db.close()
})
}
I get this error:我收到此错误:
TypeError: Cannot read property 'db' of null类型错误:无法读取 null 的属性“db”
As mentioned above, you need to log the connection error.如上所述,您需要记录连接错误。 Once you do this you'll have an idea what the connection problem is!一旦你这样做了,你就会知道连接问题是什么! Make sure also that the DB name is present in your URL!还要确保数据库名称存在于您的 URL 中!
function getallvideos(callback) {
MongoClient.connect(url, function(err, client) {
if (err) {
console.error('An error occurred connecting to MongoDB: ', err);
} else {
const db = client.db("cathub")
db.collection("videos", function (err, collection) {
collection.find().toArray(function(err, res) {
callback(res)
})
})
db.close()
}
})
}
I'd also handle the error accessing the videos collection, it'll be best in the long run!我也会处理访问视频集合的错误,从长远来看,这将是最好的!
const DB_URL = 'mongodb+srv://yourUser:yourPassword@yourCluster.mongodb.net/'
const DB_NAME = 'someDBName'
const DB_COLLECTION_NAME = 'someCollectionName'
const getData = async () => {
const client = await MongoClient.connect(DB_URL, {
useUnifiedTopology: true
}).catch((err) => {
console.log(err)
})
if (!client) {
return []
}
try {
const db = client.db(DB_NAME)
const collection = db.collection(DB_COLLECTION_NAME)
const res = await collection.find().toArray()
return res
// console.log(res)
} catch (err) {
return err
// console.log(err)
} finally {
client.close()
}
}
getData()
.then((data) => {
console.log(data)
})
.catch((err) => {
console.log(err)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.