Answers for "monoose crud"

1

monoose crud

// Basic CRUD operation with mongoDB

// GET 
app.get("/user", async (req, res) => {
  try {
    const userDetails = await Users.find({});
    res.send(userDetails);
  } catch (err) {
    console.log("~ err", err);
  }
});

// INSERT
app.post("/user", async (req, res) => {
  try {
    const newUser = new Users(req.body);

    newUser.save(function (err, data) {
      if (err) {
        console.log(error);
      } else {
        res.send("Data inserted");
      }
    });
  } catch (err) {
    console.log("~ err", err);
  }
});

// DELETE
app.delete("/user/:id", async (req, res) => {
  try {
    const id = req.params.id;
    const userDelete = await Users.remove({ _id: id });
    res.send("User deleted successfully");
  } catch (err) {
    console.log("~ err", err);
  }
});

// UPDATE
app.put("/user/:id", async (req, res) => {
  try {
    const id = req.params.id;
    const userDelete = await Users.findByIdAndUpdate(
      { _id: id },
      { ...req.body }
    );
    res.send("User updated successfully");
  } catch (err) {
    console.log("~ err", err);
  }
});
Posted by: Guest on August-26-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language