因此,我想使用邮递员发送多个数据(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});
}
});
谢谢
答案 0 :(得分:0)
很抱歉,如果您想到了这一点,但是可以在Postman中传递一个数组,然后将路由.forEach放在该数组的元素上以存储在数据库中。
如果您有时想发送单个对象,甚至可以设置条件以首先检查它是否为数组。
答案 1 :(得分:0)
您将必须将JSON作为数组发送。
[{
"title": "Asparagus",
...
}, {
"title": "Green smoothie",
...
}]
然后您可以像这样访问它:
req.body.forEach(item => {
// do something with item
})