这确实是一个重复的question,但没有答案。
问题是,当我通过post请求保存mongoose的新记录时,保存的内容如下:
{ "_id" : ObjectId("5d11590975c82f216eaa4712"), "__v" : 0 }
我遵循这个tutorial,所以代码应该工作正常,但不管它是:
** Mongoose 模式:**
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Todo = new Schema({
todo_description: {
type: String
},
todo_responsible: {
type: String
},
todo_priority: {
type: String
},
todo_completed: {
type: Boolean
}
});
module.exports = mongoose.model('Todo', Todo);
代码:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const todoRoutes = express.Router();
const PORT = 4000;
let Todo = require('./todo.model');
app.use(cors());
app.use(bodyParser.json());
mongoose.connect('mongodb://127.0.0.1:27017/todos', { useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', function() {
console.log("MongoDB database connection established successfully");
})
todoRoutes.route('/').get(function(req, res) {
Todo.find(function(err, todos) {
if (err) {
console.log(err);
} else {
res.json(todos);
}
});
});
todoRoutes.route('/:id').get(function(req, res) {
let id = req.params.id;
Todo.findById(id, function(err, todo) {
res.json(todo);
});
});
todoRoutes.route('/update/:id').post(function(req, res) {
Todo.findById(req.params.id, function(err, todo) {
if (!todo)
res.status(404).send("data is not found");
else
todo.todo_description = req.body.todo_description;
todo.todo_responsible = req.body.todo_responsible;
todo.todo_priority = req.body.todo_priority;
todo.todo_completed = req.body.todo_completed;
todo.save().then(todo => {
res.json('Todo updated!');
})
.catch(err => {
res.status(400).send("Update not possible");
});
});
});
todoRoutes.route('/add').post(function(req, res) {
let todo = new Todo(req.body);
todo.save()
.then(todo => {
res.status(200).json({'todo': 'todo added successfully'});
})
.catch(err => {
res.status(400).send('adding new todo failed');
});
});
app.use('/todos', todoRoutes);
app.listen(PORT, function() {
console.log("Server is running on Port: " + PORT);
});
发布请求:
获取请求:
为了确认,下面是mongodb中的输出:
5条答案
按热度按时间slsn1g291#
问题是主体需要是Json(application/json)而不是Text
b4wnujal2#
您的代码一切正常
只需将这一行添加到您的todo.model.js
h79rfbju3#
1:
编辑:
我也有这个问题,我修复了Content-type:应用程序/ json,它工作正常
vddsk6oq4#
请确保将app.use(express.json())添加到server.js文件中。
yqyhoc1h5#
尝试使用主体解析器并使用app.use(bodyParser.json());在app.js文件中