简体   繁体   English

如何使用参数设置快速路由

[英]How to set up an Express route with parameters

I am building a MEVN stack CRUD app (Vue, Node, Express, MongoDB).我正在构建一个 MEVN 堆栈 CRUD 应用程序(Vue、Node、Express、MongoDB)。 I am attempting to set up the following Express route for my app...我正在尝试为我的应用设置以下 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();
});

...so that it returns specific data from MongoDB based on the id of that data. ...以便它根据该数据的 id 从 MongoDB 返回特定数据。 I am not sure how to set up res.send so that it finds data based on req.params.id .我不确定如何设置res.send以便它根据req.params.id查找数据。 I tried passing in req.params.id like so...我试着像这样传入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();
});

...but that also did not work. ...但这也不起作用。 Any idea how to set up this route so that it finds data based on the ID parameter?知道如何设置此路由以根据 ID 参数查找数据吗? Thanks!谢谢!

My full Express router page is below:我的完整 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;

You had better to use findOne method like this:你最好像这样使用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);
});

You need to pass the filter in find query ie您需要在查找查询中传递过滤器,即


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

Also you can't send the response twice for one request so omit one resp.send() .此外,您不能为一个请求发送两次响应,因此请省略一个resp.send()

If you require a specific data from the DB so you need use findById method and pass your id instead of find method :如果您需要来自数据库的特定数据,则需要使用findById方法并传递您的 id 而不是find方法:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM