2 回答

TA貢獻1883條經驗 獲得超3個贊
很多nodejs的新手都是直接用mongodb本身直接操作數據庫,我之前也是如此
不知道大家有沒有遇到過這個錯誤:
Error: db object already connecting, open cannot be called multiple times
也許你會說是異步寫得不好,但是就算異步寫得再好,也逃避不了這個錯誤
因為無論如何,都要用到db.open();這東西,而且訪問完畢還得db.close();
于是就有一個問題:刷新得太快,或者多個用戶同時訪問數據庫,數據庫沒來得及關閉,那個Error就會出現
可以做一下實驗,在訪問數據庫的頁面按住F5,就會很容易看到在頁面上或者控制臺上拋出的Error勒
用mongoose就不會出現這錯誤勒,因為一旦連接好數據庫,db就會處于open狀態,不存在訪問時要打開,然后又要關閉的規則,然后我果斷把所有mongodb部分改為mongoose,按住F5毫無壓力啊,而且尼瑪代碼又短了一大截!
前后代碼對比一下:
之前每次操作要open:
User.get = function get(username, callback) {
mongodb.open(function(err, db) {
if (err) {
return callback(err);
}
//讀取 users 集合
db.collection('users', function(err, collection) {
if (err) {
mongodb.close();
return callback(err);
}
//查找 name 屬性為 username 的文檔
collection.findOne({name: username}, function(err, doc) {
mongodb.close();
if (doc) callback (err, doc);
else callback (err, null);
});
});
});
};
現在,建立好mongoose對象模型后只需幾行代碼即可實現相同的功能:
User.get = function get(username, callback) {
users.findOne({name:username}, function(err, doc){
if (err) {
return callback(err, null);
}
return callback(err, doc);
});
};

TA貢獻1829條經驗 獲得超4個贊
node.js操作mongodb提供了多種驅動,包含mongoose,mongoskin,node-mongodb-native(官方)等。
mongoose官網上作者的解釋:
Let's face it, writing MongoDB validation, casting and business logic boilerplate is a drag. That's why we wrote Mongoose.
Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box.
Mongoose庫簡而言之就是在node環境中操作MongoDB數據庫的一種便捷的封裝,一種對象模型工具,類似ORM,Mongoose將數據庫中的數據轉換為JavaScript對象以供你在應用中使用
- 2 回答
- 0 關注
- 2032 瀏覽
添加回答
舉報