2
    const user = await User.findById(req.user._id);


    // finds index of object in the array to be removed
    var indexToRemove = -1;
    for (var i = 0; i < user.weights.length; i++) {
        if (user.weights[i].date === weightInstance.date) {
            indexToRemove = i;
        }
    }

    if (indexToRemove > -1) {
        // what goes here?
    }

    user.weights.push(weightInstance);
    await user.save();

What i'm trying to do is remove a Weight subdocument object (if it exists) nested inside user (user.weights) that matches in date property with the new Weight subdocument object that I am adding into the user.weights array.

User Schema:

const userSchema = new Schema({
    googleId: String,
    weights: [Weight]
});

Weight Schema:

const weightSchema = new Schema({
    date: String,
    weight: Number
});
TQL
  • 33
  • 1
  • 4
  • Possible duplicate of [How to remove array element in mongodb?](https://stackoverflow.com/questions/16959099/how-to-remove-array-element-in-mongodb) – s7vr Jan 22 '18 at 16:34

1 Answers1

4

You can do it using the Array.filter function :

  // Get the user from database
  const user = await User.findById(req.user._id);

  // Use the function filter to remove every user
  // matching the date in weightInstance
  user.weights = user.weights.filter(x => x.date !== weightInstance.date);

  // Save the modified user
  await user.save();
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69