简体   繁体   English

在Node.js中使用猫鼬的问题

[英]questions when using mongoose in Node.js

I am learning Node.js using Beginning Node.js written by Mr. Basarat Syed. 我正在使用Basarat Syed先生编写的Beginning Node.js学习Node.js。

I have come across the following mongoose code snippet. 我遇到了以下猫鼬代码段。 My question is about the last three lines with db.close() and how does the collection tanks come up without any statement about tanks. 我的问题是关于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();});
        });
    });
});

My question is what is the difference among the last three lines? 我的问题是最后三行之间有什么区别? Where did the collection('tanks') come from? collection('tanks')来自哪里? Why not just use db.close() like the second one? 为什么不像第二个一样只使用db.close() It seems that I could use any legal string as the argument of collection on for example the third sentence 't' . 似乎我可以使用任何合法字符串作为collection的参数,例如第三句't' How could this happen? 怎么会这样

When you save an instance of the Tank model, mongoose simply infers the collection name to tanks (lowercase Tank + the s suffix), and creates the collection if needed (ie if it doesn't already exist), unless you explicitly tell it another name to use, like this: 当您保存Tank模型的实例时,猫鼬会简单地将集合名称推断为tanks (小写的Tank +后缀s ),并在需要时创建集合(即,如果它尚不存在),除非您明确地告诉另一个使用的名称,例如:

var tankSchema = new mongoose.Schema({name: 'string', size: 'string'}, { collection: 'myTanks' });

The following statement drops the tanks collection you created by saving a tank using the Tank model, and then closes the connection 以下语句删除通过使用Tank模型保存坦克而创建的tanks集合,然后关闭连接

db.collection('tanks').drop(function(){db.close();});

This statement only closes the connection, without doing anything else 该语句仅关闭连接,不执行其他任何操作

db.close();

This one drop the collection t (which I guess doesn't exist in your case), and then again closes the connection 这一次删除了集合t (我想您的情况下不存在),然后再次关闭连接

db.collection('t').drop(function(){db.close();});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM