我正在使用一种实践API来习惯于创建模型和路线,但是似乎无法获得将数据保存到MongoDB的第一条路线。
我从PostMan中收到以下错误:
{
"message": {
"errors": {
"name": {
"message": "Path `name` is required.",
"name": "ValidatorError",
"properties": {
"message": "Path `name` is required.",
"type": "required",
"path": "name"
},
"kind": "required",
"path": "name"
},
"description": {
"message": "Path `description` is required.",
"name": "ValidatorError",
"properties": {
"message": "Path `description` is required.",
"type": "required",
"path": "description"
},
"kind": "required",
"path": "description"
}
},
"_message": "Universes validation failed",
"message": "Universes validation failed: name: Path `name` is required., description: Path `description` is required.",
"name": "ValidationError"
}
} 我的模型和路线如下所示:
const mongoose = require('mongoose');
const UniverseSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
description: {
type: String,
required: true
},
date : {
type: Date,
default: Date.now
}
});
//export the route ---------------------Name in db , schema that it should use
module.exports = mongoose.model('Universes', UniverseSchema);
const express = require('express');
const router = express.Router();
const Universe = require('../models/Universe');
// Initial route that will render our universes page
router.get('/', async (req , res) => {
res.send('Universes Page');
try {
const universes = await Universe.find();
res.json(universes);
} catch (error) {
res.json({ message: error });
}
});
// Route use to create a universe
// Create async our post
router.post('/', async (req, res) => {
// Create an instance of the Universe model
const universe = new Universe({
name : req.body.name,
description : req.body.description
});
// Attempt to save our new universe with a try catch
try {
const savedUniverse = await universe.save()
res.json(savedUniverse);
console.log('saved');
} catch (error) {
res.json({ message: error});
console.log('Not saved');
}
});
module.exports = router;
每当我通过邮递员传递数据时,我都会发送带有以下对象的POST请求: { “ name”:“ test1”, “ description”:“测试说明1” } 这是我的App.js文件-包括正文解析器
//Server setup
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
require('dotenv').config();
//Middleware
app.use(bodyParser.json());
//index Route
app.get('/' , ( req , res ) => {
res.send('index');
});
// Import routes
const universeRoute = require('./routes/universes');
app.use('/universes', universeRoute );
//Connect to DB
mongoose.connect(process.env.DB_CONNECT,
{ useNewUrlParser: true } ,
() => {
console.log('Connected to DB');
});
app.listen(process.env.PORT || 5000);
感谢所有帮助。
答案 0 :(得分:1)
很有可能是您将数据发送到API的方式及其解析方式。
尝试一下:
在Postman中,使用最常用的方法格式通过POST请求发送数据。这是:“原始”并将数据作为application / json发送。
在API端,请确保您能够解析application / json请求。 Express上最常用的软件包是expressjs/body-parser
const mongoose= require('mongoose')
const express = require('express')
const bodyParser = require('body-parser')
const Universe = require('../models/Universe')
const app = express()
// Connect to MongoDB
mongoose.connect(/* MongoDB connection string */, /* Connection options */);
mongoose.connection.on('error', err => {
console.error('MongoDB connection error: ' + err)
process.exit(-1)
})
// parse JSON
app.use(bodyParser.json({ type: 'application/json' }))
// Initial route that will render our universes page
app.get('/', async (req , res) => {
res.send('Universes Page')
try {
const universes = await Universe.find()
res.json(universes)
} catch (error) {
res.json({ message: error })
}
});
// Route use to create a universe
// Create async our post
app.post('/', async (req, res) => {
// Create an instance of the Universe model
const universe = new Universe({
name : req.body.name,
description : req.body.description
})
// Attempt to save our new universe with a try catch
try {
const savedUniverse = await universe.save()
res.json(savedUniverse)
console.log('saved')
} catch (error) {
res.json({ message: error})
console.log('Not saved')
}
});
app.listen(3000)
并记得验证身体:)
希望有帮助!