如何从猫鼬中的对象数组中删除对象
how to delete object from the array of objects in mongoose
I have notes nested in userSchema I am trying to delete one object by _id but deleteOne is removing the whole user object so how can I can delete the one with _id
const keeperSchema = mongoose.Schema({
noteName:String,
noteContent:String,
})
const userSchema = mongoose.Schema({
email:String,
password:String,
notes:[keeperSchema]
})
app.post("/delete",(req,res)=>{
const id=req.body.id
const email=req.body.email
console.log(id)
Keeper.deleteOne({"notes._id":id}).then(()=>{
Keeper.find({email:email},(err,results)=>{
if(results){
console.log(results)
}
})
})
})
你可以这样做:
userModel.updateOne({_id: idofUser}, {$pull: {notes: {_id: idofnote}}})
你应该查询你的 userModel
,因为你想从存储在 user
中的 keeper 数组中提取一个元素,所以你必须确定要从哪个用户那里删除你的笔记,这就是为什么你需要有用户的ID。如果您想从所有用户中删除特定的注释,只需像这样清除您的条件:
userModel.updateMany({}, {$pull: {notes: {_id: idofnote}}})
I have notes nested in userSchema I am trying to delete one object by _id but deleteOne is removing the whole user object so how can I can delete the one with _id
const keeperSchema = mongoose.Schema({
noteName:String,
noteContent:String,
})
const userSchema = mongoose.Schema({
email:String,
password:String,
notes:[keeperSchema]
})
app.post("/delete",(req,res)=>{
const id=req.body.id
const email=req.body.email
console.log(id)
Keeper.deleteOne({"notes._id":id}).then(()=>{
Keeper.find({email:email},(err,results)=>{
if(results){
console.log(results)
}
})
})
})
你可以这样做:
userModel.updateOne({_id: idofUser}, {$pull: {notes: {_id: idofnote}}})
你应该查询你的 userModel
,因为你想从存储在 user
中的 keeper 数组中提取一个元素,所以你必须确定要从哪个用户那里删除你的笔记,这就是为什么你需要有用户的ID。如果您想从所有用户中删除特定的注释,只需像这样清除您的条件:
userModel.updateMany({}, {$pull: {notes: {_id: idofnote}}})