skip to Main Content

I have a user schema as follows:

const UserSchema = new mongoose.Schema({
 
  skills: [String]
});

module.exports = mongoose.model("User", UserSchema);

And a Fetch request to delete a skill as follows:

const deleteItem = async (id) => {
    try {
    
      await fetch(`http://localhost:5000/api/user/deleteskill`, {
        method: "DELETE",
        headers: { "Content-Type": "application/JSON", token: accessToken },
        body: JSON.stringify({ userid: userid , skill:id}),
      })
        .then((res) => res.json())
        .then((data) => {
          console.log("USER SKILLS:", data.userskills);
        });      
    } catch (err) {
      console.log(err);
    }
  };

Server

const deleteSkill = async (req, res) => {
  try {
    const user = await User.findById(req.body.userid)
    
    //user.skills.pull(req.body.skill);

    // removeskill = user.skills.filter(function(item) {
    //   return item !== req.body.skill
    // })

    if (user.skills.includes(req.body.skill)) {

      res.status(400).json("Item Still Exists");

    } else {

      res.status(200).json("Item Deleted");
    }

   
  } catch (error) {
    res.status(500).send({ error: error.message });
  }
};

the array is in the following structure

  [
  'skill1', 'java',  'skill5'
]

I have tried to remove the user skill from the array in several ways but I still get res.status(400).json("Item Still Exists");. What I’m doing wrong?

4

Answers


  1. I believe you want to remove skills from the database then the following function could help you out.

    var MongoClient = require('mongodb').MongoClient;
    var url = "mongodb://localhost:27017/";
    
    MongoClient.connect(url, function(err, db) {
     if (err) throw err;
      var dbo = db.db("mydb");
      var myquery = { userid: userid, skillid: skillid};
      dbo.collection("skills").deleteOne(myquery, function(err, obj) {
        if (err) throw err;
        console.log("1 document deleted");
        
      db.close();
     });
    });
    
    Login or Signup to reply.
  2. You have a method of removing elements from arrays, if you want to remove the first one you could use array.shift (more on it here), but if you want to delete it completely from your database you could always, find it and then update it.

    Login or Signup to reply.
  3. User.update({ _id: userid }, { $pull: { "skills": "[skill]" }})
    
    Login or Signup to reply.
  4. Use the findOneAndUpdate method to find a document with the user id and update it in one atomic operation:

    const deleteSkill = async (req, res) => {
      try {
        let message = "Item Deleted";
        let status = 200;
        const user = await User.findOneAndUpdate(
          { _id: req.body.userid },
          { $pull: { skills: req.body.skill } },
          { new: true }
        )
        
        if (user && user.skills.includes(req.body.skill)) {
          message = "Item Still Exists";
          status = 400;
        } else if (!user) {
          message = "User Not Found";
          status = 404;
        }
        
        res.status(status).send({ message });
       
      } catch (error) {
        res.status(500).send({ error: error.message });
      }
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search