我不知道我可以使用.Router()
来做到这一点。我刚够getById
我需要在POST请求上创建路由,是吗?
./ generalRepository.js
function Repository() {}
Repository.prototype.getById = getById;
function getById(id, callback) {
var model = this.model;
var query = model.findOne({
_id: id
});
query.exec(callback);
}
.routers / user.js
const router = require("express").Router();
const userService = require("../../services/user");
router.get("/:id", (req, res, next) => {
userService.findOne(String(req.params.id), (err, data) => {
if (!err) {
res.data = data;
console.log("это запрос в айди");
res.json(res.data);
} else {
console.log(Number(req.params.id));
res.status(400);
res.end();
}
});
});
module.exports = router;
.services / user.js
module.exports = {
findAll: callback => {
findOne: (id, callback) => {
UserRepository.getById(id, (err, data) => {
callback(err, data);
});
}
};
答案 0 :(得分:1)
将数据发布到Node并使用Mongoose插入数据的简单示例:
// Add these two lines so your request's body can be accessed as JSON using req.body :
const bodyParser = require("body-parser");
app.use(bodyParser.json({ limit: '1mb' }));
(new myMongooseModel(req.body)).save( (error, result) => {
if(error) return res.json(error);
res.json(result);
})