简体   繁体   中英

What is the problem in my code? How to delete a collection from MongoDB?

I am trying to delete a collection from mongodb using postmap API. Below is my code.The update function is working fine.But, delete function isn't working. It's displaying internal server error.I dont know why?

const router = require("express").Router();
const User = require("../models/User");
const bcrypt = require("bcrypt");
//uodate
router.put("/:id", async (req, res) => {
    if ((req.body.userId === req.params.id) || req.body.isAdmin) {
        if (req.body.password) {
            try {
                const salt = await bcrypt.genSalt(10);
                req.body.password = await bcrypt.hash(req.body.password, salt);
            }
            catch (err) {
                return res.status(500).json(err);
            }
        }
        try {
            const user = await User.findByIdAndUpdate(req.params.id, {
                $set: req.body,
            });
           return res.status(200).json("Account has been updated");
        }
        catch (err) {
            return res.status(500).json(err);
        }
    }
    else return req.status(400).json("You can only update your account!!!");
});
//delete
router.delete("/:id", async (req, res) => {
    if ((req.body.userId === req.params.id) || req.body.isAdmin) {
        try {
           await User.deleteOne(req.params.id);
            return res.status(200).json("Account has been deleted");
        }
        catch (err) {
            return res.status(500).json(err);
        }
    }
    else return res.status(400).json("You can only update your account!!!");
});



module.exports = router;

Help me with this postman API screenshot .

You are using deleteOne() method. If you want to delete whole collection, you should use deleteMany() method:

await User.deleteMany({});

The Model.deleteOne method expects a filter object, like {name: "value'"} . You are passing req.params.id which is a string. If you dig out the full text of the error, it will likely complain about that string not being an object.

You probably meant to use the Model.findByIdAndDelete method like

await User.findByIdAndDelete(req.params.id);

Try this:

 await User.deleteOne({_id:req.params.id});

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