gpt4 book ai didi

javascript - 我如何通过 POST 请求和 mongoose 使用 express 添加新对象?

转载 作者:行者123 更新时间:2023-11-30 14:30:18 25 4
gpt4 key购买 nike

我不知道我可以用 .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);
});
}
};

最佳答案

将数据发布到 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);
})

关于javascript - 我如何通过 POST 请求和 mongoose 使用 express 添加新对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51304067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com