node.js - MongoDB Mongoose 如何从数组中删除对象
问题描述
var UserSchema = new mongoose.Schema({
//Irrelevant code
profile:
{
requests: [{ sender: String, id: String, hasSelected: Boolean, value: Boolean}]
}
});
该对象是跟踪好友请求,我希望它在被接受或拒绝后从请求数组中完全删除。我已经尝试了一大堆东西,但没有任何东西可以删除它。目前有这个代码:
User.updateOne({ id: user.id },
{ "$pull": { "profile": { "requests": { "id": targetId } } } },
{ "multi": true },
function(err,status) {
if(err){console.log("Could not delete the friend request");}
else{
console.log("Sucessfully deleted friend request from: " + user.name);}
}
);
它总是说它已在日志中删除,但是当我检查 mongoDB 时,请求仍然存在。
解决方案
尝试 $elemMatch 删除特定对象。
User.updateOne(
{ id: user.id },
{ $pull: { "profile.requests": { $elemMatch: { id: targetId } } } },
{ multi: true },
function (err, status) {
if (err) {
console.log("Could not delete the friend request");
} else {
console.log("Sucessfully deleted friend request from: " + user.name);
}
}
);
推荐阅读
- php - 执行保存在 wp_options 表内的文本框中的 PHP 片段
- java - ByteBufferBackedInputStream 重新填充 ByteBuffer
- adobe-indesign - How to show and hide standard InDesign panels through scripting?
- powershell - 在 PowerShell 中调用静态类方法
- rust - 比较 Rust 中的字符串长度
- entity-framework - 使用 asp.net core 和 EF core 构建可定制的报告生成向导
- selenium - Jenkins 在 Firefox 上的无头测试执行
- python - 如何从 HFS 分割图像中提取轮廓
- python - 我如何轻松找到一个数字是否是 2 的幂?
- c# - 在 VS Code 中将函数名称(函数头)变为粗体