【问题标题】:How to save particular object in mongoose schema如何在猫鼬模式中保存特定对象
【发布时间】:2022-10-07 21:11:58
【问题描述】:

我在这里遇到了一些问题,我尝试只存储一个对象,无论是学校、大学还是工作,但猫鼬会自动创建另外两个对象。

如何省略其他对象。在这里我应该使用default

let mySchema = new Schema({
    "type": { type: String, default: "" },  // school or college or work
    "school": {
        'name':{ type: String, default: "" },
        'parent':{ type: String, default: "" },
        'address':{ type: String, default: "" },
        'email_id':{ type: String, default: "" },
        'phone_no':{ type: String, default: "" },
    },
    "college": {
        'name':{ type: String, default: "" },
        'friend':{ type: String, default: "" },
        'address':{ type: String, default: "" },
        'email_id':{ type: String, default: "" },
        'phone_no':{ type: String, default: "" },
    },
    "work": {
        'name':{ type: String, default: "" },
        'colleague':{ type: String, default: "" },
        'address':{ type: String, default: "" },
        'email_id':{ type: String, default: "" },
        'phone_no':{ type: String, default: "" },
    },
});

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    有什么东西可以避免你以编程方式设置它吗?

    const myType = "school"; // Just for example
    
    const mySchemaObj = { "type": { type: String, default: myType } };
    mySchemaObj[myType] = { 
        "school": {
            'name':{ type: String, default: "" },
            'parent':{ type: String, default: "" },
            'address':{ type: String, default: "" },
            'email_id':{ type: String, default: "" },
            'phone_no':{ type: String, default: "" },
        },
        "college": {
            'name':{ type: String, default: "" },
            'friend':{ type: String, default: "" },
            'address':{ type: String, default: "" },
            'email_id':{ type: String, default: "" },
            'phone_no':{ type: String, default: "" },
        },
        "work": {
            'name':{ type: String, default: "" },
            'colleague':{ type: String, default: "" },
            'address':{ type: String, default: "" },
            'email_id':{ type: String, default: "" },
            'phone_no':{ type: String, default: "" },
        }
    }[myType];
    
    console.log(mySchemaObj);
    
    /* Then, later...
    let mySchema = new Schema(mySchemaObj);
    */

    【讨论】:

      猜你喜欢
      • 2017-11-28
      • 1970-01-01
      • 2016-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-18
      • 2014-02-10
      • 2017-06-12
      相关资源
      最近更新 更多