【问题标题】:saving complex structure in mongodb using express and mongo使用 express 和 mongo 在 mongodb 中保存复杂的结构
【发布时间】:2019-04-22 06:22:17
【问题描述】:

我是 mongodb、node 和 express 的新手。我正在尝试将这些数据保存在 mongodb 中。

我有 staff.model.js 如下

let StaffSchema = new Schema({
    staffcode:String,
    firstname:String,
    lastname: String,
    type: String,
    department:String,
    dateofjoin:Date,
    lastworkingday:Date,
    teaching:[ {type:Schema.Types.ObjectId, ref:'Teaches'} ]
});

我有另一个名为“教”的架构,如下所示

let TeachesSchema = new Schema({
    standard:{type: Schema.Types.ObjectId, ref: 'Standard'},
    subjects:[{type: Schema.Types.ObjectId, ref: 'Subject'}]
});

另一种标准模式如下

let StandardSchema = new Schema({
    name:String,
    medium:String,
    section:String
});

另一种架构主题如下

let SubjectSchema = new Schema({
    name:{ type: String, required: true, max: 25 }
});

最后我尝试将数据保存在 mogodb 中

exports.staff_create = function(req, res){
    let staff = new Staff({
        staffcode:req.body.staffcode,
        firstname:req.body.firstname,
        lastname: req.body.lastname,
        type: req.body.type,
        department:req.body.department,
        dateofjoin:req.body.dateofjoin,
        teaching:req.body.teaching
    });
    staff.save(function(err){
        if(err){
            return next(err);
        }
        res.send('Staff created successfully');
    });
};

使用这样的输入从邮递员发出 api 调用

{
  "staffcode": "STF0003",
  "firstname": "Joh Doe",
  "lastname": "Moy",
  "type": "teaching",
  "department": "physics",
  "dateofjoin": "2018-06-01",
  "teaching": {
    "standard": {
      "_id": "5cb8ff551a1c1a2514fa467c",
      "name": "1",
      "medium": "English",
      "section": "A"
    },
    "subjects": [
      {
        "_id": "5cb8ed65c068b22f5489d050"
      },
      {
        "_id": "5cb8ed6bc068b22f5489d051"
      }
    ]
  }
}

这有什么问题?我无法在邮递员请求中获得成功响应。

【问题讨论】:

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


    【解决方案1】:

    您的架构设计来自关系数据库。但是,您可以使用populate 执行您所要求的操作。

    更好的方法是在某些地方使用嵌入文档而不是推荐查看有关MongoDB relationships: embed or reference?的答案

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多