【问题标题】:Express mongoose populate array of subdocuments from POSTExpress mongoose 从 POST 填充子文档数组
【发布时间】:2017-09-25 15:49:16
【问题描述】:

这是我的 Mongoose 架构:

const InvoiceSchema = new Schema({
name: { type: String, required: true },
description: { type: String },

items: [{
    product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product'},
    amount: { type: Number },
    name: { type: String, required: true },
    quantity: { type: Number },
    rate: { type: Number, required: true }
}],
createdBy: { type: Schema.ObjectId, ref: 'User', required: true },
}

现在我想从 POST 数据填充我的架构,我的问题是我不知道如何发布我的项目(如何命名我的字段)??

我使用 PostMan 发布数据。

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    批量添加项目

    const invoice = new Invoice();
    invoice.items = req.body.items;
    

    添加单个项目

    invoice.items.push(item);
    

    更新单个项目

    const item = invoice.items.id(req.params._id);
    item.attribute = ...
    // Do update
    

    【讨论】:

      【解决方案2】:

      获取帖子数据

      在 mongoose 中添加新记录

      const {ObjectId} = mongoose.Schema.Types;
      const newInvoice = new InvoiceSchema({
        name: "John Smith",
        description: "This is a description",
        items: [{
          product: 'THIS_IS_AN_OBJECT_ID_STRINGIFIED',
          amount: 2,
          quantity: 5,
          //name - comes from the product model
          //rate - comes from the product model
        }]
      });
      
      newInvoice.save();
      

      发布并保存

      //Response format
      {
        name: 'John Smith',
        description: 'This is a description',
        items: [
          {
            product: 'THIS_IS_AN_OBJECT_ID',
            amount: 2,
            quantity: 5
          }
        ]
      }
      
      app.post('/yourRoute', (req, res) => {
        const {name, description, items} = req.body;
        const newInvoice = new InvoiceSchema({name, description, items});
        newInvoice.save().then(()=>res.send('success'))
      });
      

      【讨论】:

      • 但是我应该如何在 FrontEnd 中命名我的项目字段??
      • 如果你使用的是 Postman,你可以按照我给你的格式发送 JSON。您应该能够将其放入 Postman 并让它处理请求。如果您遇到问题console.log(req.body) 并且应该将您的 POST 数据输出到您的日志中。
      • 就命名而言,它们应该在前端与后端具有相同的名称。
      • @medKHELIFI 如果我的回答对你有帮助,你能投票吗?
      • 太棒了。谢谢!
      猜你喜欢
      • 2017-03-21
      • 2017-06-06
      • 2020-12-18
      • 2017-01-27
      • 1970-01-01
      • 2014-08-16
      • 1970-01-01
      • 2020-11-21
      • 2018-08-16
      相关资源
      最近更新 更多