首页 文章

Express的mongoose从POST填充子文档数组

提问于
浏览
1

这是我的Mongoose Schema:

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发布数据 .

2 回答

  • 0

    获取发布数据

    To add a new record in 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();
    

    To POST and save it

    //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'))
    });
    
  • 1

    To bulk add items

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

    To add single item

    invoice.items.push(item);
    

    To update single item

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

相关问题