使用或不使用“new"关键字创建猫鼬模式? [英] Creating Mongoose Schemas with or without 'new' keyword?

查看:43
本文介绍了使用或不使用“new"关键字创建猫鼬模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上看到的大多数例子都像......

Most of the examples I have seen online do something like...

var UserSchema = new mongoose.Schema({
    name: String,
    age: String
});

然而,最近我发现一本书做了上述...但没有 new 关键字.

However, recently I found a book do the above... but without the new keyword.

var UserSchema = mongoose.Schema({
    name: String,
    age: String
});

我现在很困惑.我们是否使用 new 关键字来创建架构......在这两种情况下会发生什么?

I am now confused. Do we use the new keyword for creating the schema or not.. and what happens in both cases?

推荐答案

两者都有效并返回 Mongoose.Schema 类的新实例.这意味着两者的作用完全相同.此检查您是否已经有一个实例Schema 类,如果没有,它会为您返回一个.

Both are valid and returns a new instance of the Mongoose.Schema class. What this means is that both does exactly the same. This line checks whether you already have an instance of the Schema class, if not, it returns one for you.

总结一下,如果你打电话

To summarize, if you call

var schema = new mongoose.Schema({})

你自己初始化一个实例,而如果你调用

you initialize an instance yourself, while if you call

var schema = mongoose.Schema({})

mongoose 为您初始化一个,如下:

mongoose initializes one for you, with this:

function Schema(obj, options) {
  if (!(this instanceof Schema)) {
    return new Schema(obj, options);
  }
  ...

这篇关于使用或不使用“new"关键字创建猫鼬模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆