如何使用 Mongodb 创建模型?

时间:2021-01-03 22:13:09

标签: mongodb mongoose-schema

我正在学习如何使用 Mongodb,我想知道是否有类似的方法可以使用 Mongodb 来创建架构而不使用 Mongoose。我想确保我对 Mongodb 有很好的了解。目前,我的应用可以运行,但我的请求都在 server.js 文件中,所以我正在尝试拆分文件。

例如,这里是使用 Mongoose 识别用户架构的代码。 Mongodb 有没有办法做到这一点?

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Schema
const UserSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now
  }
});
module.exports = User = mongoose.model("users", UserSchema);

1 个答案:

答案 0 :(得分:0)

MongoDB 默认是无模式的,这意味着你可以在没有预定义模式的情况下插入文档,但如果你需要对集合应用特定的规则和约束,你可以添加模式验证器,如下所示:

db.createCollection("users", {
 validator: {
  $jsonSchema: {
     bsonType: "object",
     required: [ "name", "email", "password" ],
     properties: {
        name: {
           bsonType: "string",
           description: "must be a string and is required"
        },
        email: {
                 bsonType: "string",
                 description: "must be a string and is required"
              },
        password: {
                 bsonType: "string",
                 description: "must be a string and is required"
              },
          date:   {
                 bsonType: "Date",
                 description: "must be a Date but is not required"
              } 
              
           }
        }
     }
   }
 }
})