首页 > 解决方案 > mongoose.Schema 在猫鼬中返回什么?

问题描述

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const modelSchema = new Schema({
    a: String,
    b: Date
});

我知道第一行返回一只猫鼬。但是 mongoose.Schema 在这段代码中究竟返回了什么?为什么我们需要它来写第三行,“const modelSchema = new Schema(...)”?

标签: javascriptmongoose

解决方案


你不必。

它只是节省时间写作的捷径mongoose.Schema......上面的代码:

const mongoose = require('mongoose'); 

const Schema = mongoose.Schema;

const modelSchema = new Schema({
    a: String,
    b: Date
});

相当于:

const mongoose = require('mongoose');

const modelSchema = new mongoose.Schema({
    a: String,
    b: Date
});

因此,要回答您的问题,仅引用 the 的行mongoose.Schema无非是shortcut为了节省mongoose.您每次都写额外的东西:)。

经常使用它的主要原因是因为很多示例都schema在文件/示例中定义了多个示例。因此,为了节省时间,并且每次仅使用变量引用它时都不要重复相同的属性路径Schema


推荐阅读