如何在mongoose或mongodb中创建数据模型

olhwl3o2  于 2023-01-30  发布在  Go
关注(0)|答案(2)|浏览(161)

比方说,我有一些数据,包含州(国家),省,和年,和条件,我会尝试解释这个如下:

state_a: {
    province: {
        name: 'prov_1',
        conditions: {
           year: 2019,
           condition: 'normal'
        },
        conditions: {
           year: 2020,
           condition: 'not normal'
        }
    },
    province: {
        name: 'prov_b',
        conditions: {
           year: 2019,
           condition: 'not normal'
        },
        conditions: {
           year: 2020,
           condition: 'not normal'
        }
    }
},
state_b: ......... etc

事实上,我不知道如何解释它:D,我希望代码能解释我的意思。我想在 Mongoose 创建模型。你能帮助我吗,伙计们?

py49o6xq

py49o6xq1#

你得做些这样的事。

const dataSchema =  new mongoose.Schema({
State: {
        type: String,
        required: true
       },
Province: [{
        name: {
            type: String;
            required: true
           }
        conditions: [
        { 
           year: { 
              type: Number,
              required: true
              },

           condition: {
              type: String,
              required: true
              }
         }]

    }]

})
ar7v8xwq

ar7v8xwq2#

首先安装mongoose npm i mongoose
然后,插入以下代码

const mongoose = require('mongoose');
const Schema = mongoose.Schema

const stateSchema = new Schema({
  state: {
    province: [
      {
      name: String,
      conditions: {
        year: Date,
        condition: {type: String, enum: ['normal', 'not normal']},
        }
      },
      {
        name: String,
        conditions: {
          year: Date,
          condition: {type: String, enum: ['normal', 'not normal']},
          }
        },
    ]
  }
})

const state = mongoose.model('state', stateSchema)

相关问题