monoose crud

Solutions on MaxInterview for monoose crud by the best coders in the world

showing results for - "monoose crud"
Emmanuel
17 Sep 2016
1// Basic CRUD operation with mongoDB
2
3// GET 
4app.get("/user", async (req, res) => {
5  try {
6    const userDetails = await Users.find({});
7    res.send(userDetails);
8  } catch (err) {
9    console.log("~ err", err);
10  }
11});
12
13// INSERT
14app.post("/user", async (req, res) => {
15  try {
16    const newUser = new Users(req.body);
17
18    newUser.save(function (err, data) {
19      if (err) {
20        console.log(error);
21      } else {
22        res.send("Data inserted");
23      }
24    });
25  } catch (err) {
26    console.log("~ err", err);
27  }
28});
29
30// DELETE
31app.delete("/user/:id", async (req, res) => {
32  try {
33    const id = req.params.id;
34    const userDelete = await Users.remove({ _id: id });
35    res.send("User deleted successfully");
36  } catch (err) {
37    console.log("~ err", err);
38  }
39});
40
41// UPDATE
42app.put("/user/:id", async (req, res) => {
43  try {
44    const id = req.params.id;
45    const userDelete = await Users.findByIdAndUpdate(
46      { _id: id },
47      { ...req.body }
48    );
49    res.send("User updated successfully");
50  } catch (err) {
51    console.log("~ err", err);
52  }
53});