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();
我要做的是删除一个Weight子文档对象(如果存在)嵌套在用户(user.weights)中,该对象在date属性中与我添加到user.weights数组中的新Weight子文档对象相匹配
用户架构:
const userSchema = new Schema({
googleId: String,
weights: [Weight]
});
体重模式:
const weightSchema = new Schema({
date: String,
weight: Number
});
答案 0 :(得分:1)
您可以使用Array.filter功能执行此操作:
// 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();