簡體   English   中英

使用 postman 將 nodejs 上的多個數據發送到 mongodb

[英]Send multiple data on nodejs to mongodb using postman

所以,我想使用 postman 發送多個數據(json)。 例如,我有兩個數據 json。 我想同時使用 postman 將 json 發送到 mongodb 。 但我有一個錯誤

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

所以我嘗試將 object 包裝到數組中。 我得到了一個錯誤

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 。 不只是一兩個。 喜歡十個或更多,但只發送一次。

示例 json 我想發送到 mongodb

{
  "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});
  }
});

謝謝

抱歉,如果您想到了這一點,但是可以在 Postman 中傳遞一個數組,然后將您的 route.forEach 放在數組的元素上以存儲在數據庫中。

如果您有時想要發送單個 object,您甚至可以設置一個條件來首先檢查它是否是一個數組。

您必須將 JSON 作為數組發送。

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

然后你可以像這樣訪問它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM