如何解决保存到mongoDB的数据的访问ID
我有一个 POST 请求,它将数据保存到数据库,然后运行 puppeteer 以根据刚刚保存的数据创建一个 pdf。 Puppeteer 访问 URL(获取请求 /:id)并生成该页面的 PDF。这一切都发生在单个 POST 请求上。
我需要将保存在 POST 请求中的数据的 ID 传递给一个变量,该变量将允许我将 ID 动态添加到 puppeteer 中使用的 url。这意味着当 puppeteer 向 http://localhost:3000/${id} 发出 GET 请求时,会访问数据库中的正确数据。使用正确的 ID,正确的数据会使用 EJS 动态传递到我的视图。这意味着 puppeteer 根据保存在 POST 请求中的数据生成 PDF。
在概念层面上 - 我的应用程序无法仅在 POST 请求中自动知道我要查找的数据 ID。所以这是我能想到的唯一方法。
我的代码无法正常工作,因为 ID 没有传递到 URL await page.goto(
http://localhost:3000/${id}``。我哪里错了?我已经被困在这个问题上 2 周了,但找不到解决方案。
感谢您的帮助。
/* routes */
app.get("/form",(req,res) => {
res.render("index");
});
app.get("/:id",res) => {
const id = params.id;
Blog.findById(id).then((result) => {
res.render("pdf",{ blog: result });
});
});
app.post("/",res) => {
const blog = new Blog({
name: "Smileh",surname: "Smith",boiler: "ideal",installprice: "fiver",pmhun: "forty",pmsixty: "thirty",pmtwenty: "twenty",fuel: "gas",location: "kitchen",orientation: "vertical",ladders: "no",scaffolding: "no"
});
blog.save().then((result) => {
//I need the ID of the data just saved to the database
let id = {result.id}(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// I need to pass the data ID here into the URL
await page.goto(`http://localhost:3000/${id}`,{
waitUntil: "networkidle2"
});
await page.pdf({
path: "quote8.pdf",format: "A2",printBackground: true
});
await browser.close();
})();
});
});
解决方法
let id = result._id
而不是 let id = {result.id}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。