【发布时间】: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