[英]questions when using mongoose in Node.js
我正在使用Basarat Syed先生編寫的Beginning Node.js學習Node.js。
我遇到了以下貓鼬代碼段。 我的問題是關於db.close()
的最后三行,以及收集tanks
如何在沒有關於罐的任何聲明的情況下出現。
var mongoose = require('mongoose');
var tankSchema = new mongoose.Schema({name: 'string', size: 'string'});
tankSchema.methods.print = function () {
console.log('I am', this.name, 'the', this.size)
};
var Tank = mongoose.model('Tank', tankSchema);
mongoose.connect('mongodb://127.0.0.1:27017/demo');
var db = mongoose.connection;
db.once('open', function callback() {
console.log('connected!');
var tony = new Tank({
name: 'tony',
size: 'small'
});
tony.print();
tony.save(function (err) {
if (err) throw err;
Tank.findOne({name: 'tony'}).exec(function (err, tank) {
tank.print();
//======Here are the three lines=======
db.collection('tanks').drop(function(){db.close();});// The one in the book.
//db.close();
//db.collection('t').drop(function(){db.close();});
});
});
});
我的問題是最后三行之間有什么區別? collection('tanks')
來自哪里? 為什么不像第二個一樣只使用db.close()
? 似乎我可以使用任何合法字符串作為collection的參數,例如第三句't'
。 怎么會這樣
當您保存Tank
模型的實例時,貓鼬會簡單地將集合名稱推斷為tanks
(小寫的Tank
+后綴s
),並在需要時創建集合(即,如果它尚不存在),除非您明確地告訴另一個使用的名稱,例如:
var tankSchema = new mongoose.Schema({name: 'string', size: 'string'}, { collection: 'myTanks' });
以下語句刪除通過使用Tank
模型保存坦克而創建的tanks
集合,然后關閉連接
db.collection('tanks').drop(function(){db.close();});
該語句僅關閉連接,不執行其他任何操作
db.close();
這一次刪除了集合t
(我想您的情況下不存在),然后再次關閉連接
db.collection('t').drop(function(){db.close();});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.