如何在mongoose中关联数据模式

时间:2018-04-09 05:48:20

标签: node.js mongodb mongoose

我试图在nodejs / mongoose app上关联2个架构。 我的第一个模特:

var mongoose = require("mongoose");
var projectSchema = new Schema({
  pname: String,
  pnumber: String,
  plocation: String,
  pclient: String,
  clientabn: String,
  contname: String,
  contnumber: String,
  mobile: String,
  address: String,
  city: String,
  country: String,
  boqs: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: "Boq",
  }]
});

module.exports = mongoose.model("Project", projectSchema);

第二种模式:

var mongoose = require("mongoose");
var boqSchema = new Schema({
    boqDesc: String,
    boqUnit: String,
    boqQty: String,
    boqRate: String,
    boqPrice: String,

});

module.exports = mongoose.model("Boq", boqSchema);

这是我的职位溃败:

app.post("/myprojects/:id/boq", function(req, res) {
  Project.findById(req.params.id, function(err, project) {
    if (err) {
      console.log(err);
    } else {
      Boq.create(req.body.boq, function(err, boq) {
        if (err) {
          console.log(err);
        } else {
          project.boqs.push(boq);
          project.save();
          res.redirect("/myprojects/" + project._id + "/boq");
          console.log(boq);
        }
      });
    }
  });
});

何时发布,只有boq的id将保存在数据库中,而不是来自boq表单的任何数据。谁都知道这段代码有什么问题? console.log的输出: console.log output

console.log(project)

以下是帖子表格:

<form action="/myprojects/<%= project._id %>/boq" method="POST">
   <table class="table" id="toptab">
      <tbody>
         <tr>
            <td class="td6"><b>No.</b></td>
            <td class="td7"><b>Item Description/Scope of Work</b></td>
            <td class="td8"><b>Unit</b></td>
            <td class="td9"><b>Quantity</b></td>
            <td class="td10"><b>Rate</b></td>
            <td class="td11"><b>Price</b></td>
         </tr>
         <tr>
            <td class="td6"></td>
            <td class="td7" contenteditable="true" name="boq[boqDesc]"></td>
            <td class="td8" contenteditable="true" name="boq[boqUnit]"></td>
            <td class="td9" contenteditable="true" name="boq[boqQty]"></td>
            <td class="td10" contenteditable="true" name="boq[boqRate]">$</td>
            <td class="td11" contenteditable="true" name="boq[boqPrice]"></td>
         </tr>
      </tbody>
   </table>
   <button type="submit" name="submit" class="btn btn-primary">Save</button>
</form>

1 个答案:

答案 0 :(得分:0)

您正在致电Boq.create(undefined, callback);

这会在db中创建一个没有字段的boq文档(除了_id)。

它通过验证,因为不需要所有boq的字段。

转到您的客户端,并确保您正确地将boq数据添加到http请求的正文中。

<input>个标记之间添加<td></td>个元素,每个标记都以boq架构中的一个字段命名。例如<td><input type="text" name="boqDesc"></td>