gpt4 book ai didi

javascript - 如何使用参数设置 Express 路线

转载 作者:行者123 更新时间:2023-12-02 21:35:04 25 4
gpt4 key购买 nike

我正在构建一个 MEVN 堆栈 CRUD 应用程序(Vue、Node、Express、MongoDB)。我正在尝试为我的应用程序设置以下 Express 路线...

postRoutes.get('/view/:id', async (req, res) => {
const collection = await loadPostsCollection();
let id = req.params.id;
res.send(await collection.find({}).toArray());
res.status(201).send();
});

...以便它根据数据的 id 从 MongoDB 返回特定数据。我不确定如何设置 res.send 以便它根据 req.params.id 查找数据。我尝试像这样传递 req.params.id ...

postRoutes.get('/edit/:id', async (req, res) => {
const collection = await loadPostsCollection();
let id = req.params.id;
res.send(await collection.find({ _id: mongodb.ObjectId(req.params.id)}).toArray());
res.status(201).send();
});

...但这也不起作用。知道如何设置此路由以便它根据 ID 参数查找数据吗?谢谢!

我的完整 Express 路由器页面如下:

const express = require('express');
const postRoutes = express.Router();
const mongodb = require('mongodb')


postRoutes.get('/', async (req, res) => {
const collection = await loadPostsCollection();
res.send(await collection.find({}).toArray());
});


postRoutes.post('/add', async (req, res) => {
const collection = await loadPostsCollection();
let task = req.body;
await collection.insertOne(task);
res.status(201).send();
});

postRoutes.get('/view/:id', async (req, res) => {
const collection = await loadPostsCollection();
let id = req.params.id;
res.send(await collection.find({}).toArray());
res.status(201).send();
});

postRoutes.delete('/delete/:id', async (req, res, next) => {
const collection = await loadPostsCollection();
collection.deleteOne({ _id: mongodb.ObjectId(req.params.id) });
res.status(200).send({});
});

async function loadPostsCollection() {
const client = await mongodb.MongoClient.connect(
'...',
{
useNewUrlParser: true
}
);
return client.db("test").collection("todos")
}

module.exports = postRoutes;

最佳答案

你最好使用 findOne 方法,如下所示:

const { ObjectID } = require("mongodb");

postRoutes.get("/view/:id", async (req, res) => {
const collection = await loadPostsCollection();
let id = req.params.id;

let result = await collection.findOne({
_id: new ObjectID(id)
});

if (!result) {
return res.status(400).send("Not found");
}

res.status(200).send(result);
});

关于javascript - 如何使用参数设置 Express 路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60519565/

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