【问题标题】:Send multiple data on nodejs to mongodb using postman使用邮递员将nodejs上的多个数据发送到mongodb
【发布时间】:2020-06-21 18:39:39
【问题描述】:

所以,我想使用邮递员发送多个数据(json)。例如我有两个数据 json。我想像这样同时使用邮递员将该json发送到mongodb。但是我遇到了错误

SyntaxError: Unexpected token , in JSON at position 168<br> and so on.

所以我尝试将该对象包装到数组中。我得到了一个错误

Products validation failed: title: Path `title` is required., type: Path `type` is required., description: Path `description` is required., filename: Path `filename` is required., price: Path `price` is required., rating: Path `rating` is required.

我确定所有数据都已填满。

我的目标是发送大量这样的数据 json。不只是一两个。喜欢十个或更多,但只发送一次。

我要发送到 mongodb 的示例 json

{
  "title": "Asparagus",
  "type": "vegetable",
  "description": "Asparagus with ham on the wooden table",
  "filename": "2.jpg",
  "price": "18.95",
  "rating": "3"
}, {
  "title": "Green smoothie",
  "type": "dairy",
  "description": "Glass of green smoothie with quail egg's yolk, served with cocktail tube, green apple and baby spinach leaves over tin surface.",
  "filename": "3.jpg",
  "price": "17.68",
  "rating": "4"
}

架构

const productSchema = new mongoose.Schema({
    title: {type: String, required: true},
    type: {type: String, required: true},
    description: {type: String, required: true},
    filename: {type: String, required: true},
    price: {type: Number, required: true},
    rating: {type: Number, required: true},
    date: {type: Date, default: Date.now}
});

路线(发布路线)

const Product = require('../models/product.js');
routes.post('/', async (req, res) => {
  const product = new Product({
    title: req.body.title,
    type: req.body.type,
    description: req.body.description,
    filename: req.body.filename,
    price: req.body.price,
    rating: req.body.rating
  });
  try {
    const new_product = await product.save();
    return res.status(201).json(new_product);
  }catch(err){
    return res.status(400).json({error: err.message});
  }
});

谢谢

【问题讨论】:

    标签: javascript node.js mongodb mongoose rest


    【解决方案1】:

    抱歉,如果您想到了这一点,但可以在 Postman 中传递一个数组,然后将您的路由 .forEach 放在数组的元素上以存储在数据库中。

    如果您有时想要发送单个对象,您甚至可以先设置一个条件来检查它是否是一个数组。

    【讨论】:

      【解决方案2】:

      您必须将 JSON 作为数组发送。

      [{
        "title": "Asparagus",
        ...
      }, {
        "title": "Green smoothie",
        ...
      }]
      

      然后你可以这样访问它:

      req.body.forEach(item => {
        // do something with item
      })
      

      【讨论】:

        猜你喜欢
        • 2022-01-25
        • 2020-06-23
        • 2019-06-15
        • 2018-05-30
        • 2020-04-07
        • 1970-01-01
        • 2021-07-13
        • 1970-01-01
        • 2015-03-21
        相关资源
        最近更新 更多