我正在尝试构建一个 Node API,它使用 MongoDB 创建并从包含以下 JSON 格式的图书信息的文件中获取信息:
{
Name: String,
Author: String,
Price: Number
}
我无法向数据库添加信息。不过,我收到了书籍打印成功的消息。但是当我看到数据库时,仅使用 ID
和版本 key _v
创建 JSON 文档。
下面是我的 API 代码:
var express = require('express');
var app = express();
var bodyParser=require('body-parser');
var mongoose=require('mongoose');
var book = require('./automobile/reading/book')
//configuring the app for the bosy data intake for post operations
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
var PORT= process.env.PORT || 3000;
mongoose.connect('mongodb://localhost:27017/helloworldapi');
var router = express.Router();
app.use('/api', router);
router.use(function(req,res,next){
console.log('There is something happening in the API');
next();
})
router.route('/books')
.post(function(req,res){
var bookDB = new book();
bookDB.name=req.body.name;
bookDB.author=req.body.author;
bookDB.price=req.body.price;
bookDB.save(function(err){
if(err){
res.send(err);
}
res.json({message: 'Book was successfully printed'});
});
})
.get(function(req,res){
book.find(function(err, books){
if(err){
res.send(err);
}
res.json(books);
});
});
router.route('/books/:book_id')
.get(function(req,res){
book.findById(req.params.book_id, function(err, books){
if(err){
res.send(err);
}
res.json(books)
});
});
router.route('/books/name/:name')
.get(function(req,res){
book.find({name:req.params.name}, function(err, books){
if(err){
res.send(err);
}
res.json(books);
});
});
router.route('/books/author/:author')
.get(function(req,res){
book.find({author:req.params.author}, function(err, books){
if(err){
res.send(err);
}
res.json(books);
});
});
app.listen(PORT);
console.log('server listening on port '+PORT);
在执行 POST
操作后尝试执行 GET
操作时,我收到以下响应:
[
{
"_id": "5a788cf1ad829e3aa4b91287",
"__v": 0
}
]
下面是我的示意图:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BookSchema = new Schema({
Name: String,
Author: String,
Price: Number
});
module.exports= mongoose.model('book',BookSchema);
请不要介意根文件夹automobiles
。一开始就计划创建其他东西。
最佳答案
您可以使用
router.route('/books')
.post(function(req,res){
var bookDB = new book(req.body);
bookDB.save(function(err){
if(err){
res.send(err);
}
res.json({message: 'Book was successfully printed'});
});
})
但是 req.body 值在架构值上应该相同。
关于javascript - JSON 数据未添加到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48627961/