![](/img/trans.png)
[英]Node.js and mongodb: TypeError: Cannot read property 'findAll' of undefined
[英]'Cannot read property 'collection' of undefined' in mongodb and node.js
我以前使用的收集功能遇到類型錯誤。
該代碼以前在我的其他項目中工作過。 我剛剛結束了很多代碼的循環,而現在我卻遇到了這個錯誤。 我的mongodb連接代碼在另一個文件中並已連接。
var expect = require('chai').expect;
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectId;
var mongo = require('mongodb').MongoClient;
var db = require('mongodb').MongoClient;
module.exports = function (app ,db) {
db.collection.insertOne({
"title": req.body.title,
"_id": Math.random
}).touchEvent(doc =>
res.status(200).json({
"status":"success",
"_id": req.body._id,
"title": req.body.title
})).catch(err => {throw err;});
})
};
確切的錯誤消息是“ TypeError:無法讀取未定義的屬性'collection'”。 任何幫助,將不勝感激 :)
在您的情況下, db.collection.insertOne(
)行中的db
是傳遞給函數的內容,而不是文件前面定義的db
。這可能會造成混淆,因為兩個變量都命名為db
,但實際上它們是兩個不同的東西。
有關JavaScript作用域的更多信息,請參見: JavaScript中變量的作用域是什么?
試試這個:使db變量成為全局變量,然后像這樣在函數內部調用它
global.db = require('mongodb').MongoClient;
module.exports = function (app) {
db.collection.insertOne({
"title": req.body.title,
"_id": Math.random
}).touchEvent(doc => res.status(200).json({
"status":"success",
"_id": req.body._id,
"title": req.body.title
})).catch(err => {throw err;});
})
};
在這里檢查
希望對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.