阵列架构上的Node.js RESTful API验证错误

时间:2018-09-18 17:41:32

标签: javascript arrays node.js rest api-design


我按照Acedemind的教程,使用Node.js和mongoose创建RESTful API。我已经使其工作正常,现在正在扩展它,以允许客户以相同的顺序发布多个产品。基本上,我将一个简单的“ POST”请求修改为数组而不是某些变量。我的问题是,我遇到了一个很长的验证错误,该错误阻止了数组的创建。这是发布请求的代码:

    router.post("/", async (req, res, next) => {

      const productsMaybeFalses = await Promise.all(req.body.products.map(async ({ productId })=> {
        const product = await Product.findById(productId);
    if (!product) {
      return false;
    }

    return {
      ...product,
      productId,
    }
  }));

  const errors = productsMaybeFalses
    .map((productMaybeFalse, index) => {
      return {
        productMaybeFalse, index
      }
    })
    .filter(({ productMaybeFalse }) => !productMaybeFalse)

  if (errors.length) {
    console.log(error);
    return;
  }

  console.log(productsMaybeFalses);

  const products = productsMaybeFalses
    .filter((productMaybeFalse) => productMaybeFalse);


  const order = new Order({
    _id: mongoose.Types.ObjectId(),
    products: products
  });

  return order.save().then(results => {
    console.log(results);
    res.status(201).json(results.map((result) => ({
      message: "order stored",
      createdOrder: {
        _id: result._id
        },
        request: {
          type: "GET",
          url: "http://localhost:3000/orders/" + result._id
        }
    })));
  })

  .catch(err => {
    console.log(err);
    res.status(500).json({
      error: err
    })
  })
})

这是订单的架构:

    const mongoose = require("mongoose");

const pSchema = mongoose.Schema({
  productId: { type: mongoose.Schema.Types.ObjectId, ref: "Product", required: true},
  quantity: { type: Number, default: 1}
});

const orderSchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  products: [pSchema]
});

module.exports = mongoose.model("Order", orderSchema)

为了避免这个问题过长,我将仅发布错误的结尾部分。我觉得可以告诉最多信息的部分是问题所在。如果有人希望整个错误消息能更好地理解问题,并可能为我提出解决方案,我也将非常乐意将其发布。在这里:

kind: 'Array',
        value: [Array],
        path: 'products',
        reason: TypeError: value[i].toObject is not a function
    at DocumentArray.cast (/Users/axelhagman/Documents/Jacobs/node_modules/mongoose/lib/schema/documentarray.js:309:27)
    at DocumentArray.SchemaType.applySetters (/Users/axelhagman/Documents/Jacobs/node_modules/mongoose/lib/schematype.js:755:12)
    at model.$set (/Users/axelhagman/Documents/Jacobs/node_modules/mongoose/lib/document.js:922:18)
    at model._handleIndex (/Users/axelhagman/Documents/Jacobs/node_modules/mongoose/lib/document.js:740:14)
    at model.$set (/Users/axelhagman/Documents/Jacobs/node_modules/mongoose/lib/document.js:697:22)
    at model.Document (/Users/axelhagman/Documents/Jacobs/node_modules/mongoose/lib/document.js:114:12)
    at model.Model (/Users/axelhagman/Documents/Jacobs/node_modules/mongoose/lib/model.js:73:12)
    at new model (/Users/axelhagman/Documents/Jacobs/node_modules/mongoose/lib/model.js:4324:13)
    at router.post (/Users/axelhagman/Documents/Jacobs/api/routes/orders.js:70:17)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:189:7) } },
  _message: 'Order validation failed',
  name: 'ValidationError' }
POST /orders/ 500 440.085 ms - 7622

我对使用node.js和整体创建API还是很陌生,因此非常感谢您的帮助。谢谢!

0 个答案:

没有答案