简体   繁体   中英

How to set up an Express route with parameters

I am building a MEVN stack CRUD app (Vue, Node, Express, MongoDB). I am attempting to set up the following Express route for my app...

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. I am not sure how to set up res.send so that it finds data based on req.params.id . I tried passing in req.params.id like so...

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? Thanks!

My full Express router page is below:

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:

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() .

If you require a specific data from the DB so you need use findById method and pass your id instead of find method :

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({}); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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