我正在嘗試連接到 mongodb。我剛剛開始網路開發。
這是我的 database.js 代碼:
const mongodb= require('mongodb');
const MongoClient = mongodb.MongoClient;
let _db;
const mongoConnect= callback=>{
MongoClient.connect('mongodb srv://pawan:*************@cluster0.vchvo.mongodb.net/myFirstDatabase?retryWrites=true&w=majority')
.then(client=>{
console.log('connected');
_db= client.db();
callback();
})
.catch(err=>{
console.log(err);
throw err;
})
}
const getDb=()=>{
if(_db){
return _db;
}
throw 'no database found';
};
exports.mongoConnect= mongoConnect;
exports.getDb= getDb;
(我已將密碼更改為 ******** 僅針對此問題)
這是 Product.js(model) 代碼
const mongodb = require('mongodb');
const getDb = require('../Util/database').getDb;
class Product {
constructor(title, price, description) {
this.title = title;
this.price = price;
this.description = description;
}
save() {
const db = getDb();
return db.collection('products')
.insertOne(this)
.then(result=>{
console.log(result);
})
.catch(err=>{
console.log("error from save in model" err);
})
}
}
module.exports= Product;
運行我的節點應用程式后,我可以在控制臺上查看“已連接”。當_db= client.db();我在該行之后console.log(_db)我得到結果,[Object Object]
但是當我呼叫它_db時,save() method of product.js model to establish connection我得到它的值,undefined因為我得到了最終結果no database found
請指導我,以便我能找出我錯過了什么?
uj5u.com熱心網友回復:
看來,一個小的錯字是問題所在。你必須改變require在宣告app.js。改變這個:
const mongoConnect = require('./util/database').mongoConnect;
到
const mongoConnect = require('./Util/database').mongoConnect;
你看到大寫了U嗎?
解釋
當匯入./util/databaseand ./Util/database(注意大寫U)然后node將這些檔案視為不同的,因為路徑不完全相同。Windows 實際上確實指向完全相同的檔案,但nodejs快取將它們視為不同的檔案,為什么該檔案被執行兩次,而您的_db變數實際上是在第二次呼叫中新宣告的。
這是一個非常令人困惑的問題,只發生在 Windows 上。例如,Linux 會以不同的方式對待這些路徑!.
展示柜
這是一個確切顯示問題的示例。
value.js
var value = 'NOT SET'
function setContent(_value) {
value = _value
}
function getContent() {
return value
}
exports.setContent = setContent
exports.getContent = getContent
和 index.js
var { setContent } = require('./value')
setContent('New Value')
// import from same file, using the exact same path as setCOntent
var lowerCase = require('./value').getContent
// Note the uppercase "V" within the require.
var upperCase = require('./Value').getContent
console.log('LowerCase Import value (correct import.):', lowerCase())
console.log('UpperCase Import value (false import.):', upperCase())
輸出
LowerCase Import value (correct import.): New Value
UpperCase Import value (false import.): NOT SET
如您所見,對于不同的檔案路徑,同一個檔案將被執行兩次。也許有人可以在linux上嘗試?如果是相同的行為?
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/377425.html
