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
});
1

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.