0

I have the following Schema:

// userSchema
{
  _id: Schema.ObjectId,
  email: { type: String, unique: true },
  password: String,
  boxes: [boxSchema]
}
// boxSchema
{
  _id: Schema.ObjectId,
  boxId: { type: String, unique: true },
  boxName: String
}

I have data like this:

{
 _id: random,
 email: [email protected],
 password: hash,
 boxes: [{ "boxId" : "box1", "boxName" : "Box 1"}, 
  { "boxId" : "box2","boxName" : "Box 2"},
  { "boxId" : "box3","boxName" : "Box 3"}]
}

I am trying to remove an element from boxes array with boxId: box1 and the code I tried was this:

User.findOne({
        _id: req.body.id
    })
    .then(function (user) {
        if (user) {
            for (i in user.boxes)
                if (user.boxes[i].boxId === 'box1')
                   user.boxes[i].remove();
            res.json('removed');
        }
    })
    .catch(function (err) {
        ....
    });

But what happens is that it removes all the boxes which is residing, instead of the boxId: box1

2 Answers 2

2

What about using filter

User.findOne({
    _id: req.body.id
})
.then(function (user) {
    if (user) {

        user.boxes = user.boxes.filter(function(box){
            return box.boxId !== 'box1'
        })

        res.json('removed');
     }
 })
.catch(function (err) {
    ....
});
Sign up to request clarification or add additional context in comments.

Comments

0

There are many ways to remove element from the array and are as follows:

1) Delete(): using this function will remove the element but will not change the array size and keep blank object after removal of element.

2)splice(): It works similar to delete() but remove blank places in array after removal of element.

3)filter(): It takes function as an argument and removes the element efficiently.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.