node.js - 如何在mongo中删除选定的文档数组
问题描述
我必须找到商店才能从他们的成员中删除他们的 id,所以我选择了他们,我想将相同的查询与 deleteMany 一起使用不是一个好主意。这是我的代码:
async function deleteStores() {
const stores = await Store.find({
$or: [
{ deleteDate: { $exists: true, $gt: Date.now() } },
{ expires: { $gt: Date.now() + 30 * 24 * 60 * 60 * 1000 } },
],
}).populate("members");
const memberIds = [];
stores.forEach((store) => {
memberIds.push(...store.members.map((m) => m.account));
});
const storeIds = stores.map((s) => s.id);
await Account.updateMany(
{ _id: { $in: memberIds } },
{ $pull: { stores: { $in: storeIds } } }
);
// what shall I do here to delete "stores"?
}
我是 mongodb 的新手,请随时改进我的代码。
// here are my schemas
const storeSchema = new Schema({
// ... some other stuff
members: [memberSchema],
expires: { type: Date, default: () => Date.now() + 15 * 24 * 60 * 60 * 1000 },
deleteDate: Date,
});
const memberSchema = new Schema({
account: { type: Schema.Types.ObjectId, ref: "Account" },
memberType: { type: Number, enum: Object.values(MemberType), default: 3 }, // MemberType
access: [{ type: String, enum: Object.values(MemberAccess) }], // MemberAccess
});
const AccountSchema = new Schema({
// ... some other stuff
stores: [{ type: Schema.Types.ObjectId, ref: "Store" }],
});
解决方案
我认为您的代码几乎可以,在您从 Accounts 中提取商店 id 后,您应该按 id 删除商店:
await Store.deleteMany({ _id: { $in: storeIds } })
正如我所看到的,您使用的是 Mongoose,因此您应该_id
在代码中使用 not id
。如果您的代码没有store
从 Accounts 中删除引用,这就是我猜的原因。
在您的代码中,您有一个forEach
过度商店来收集成员 ID,并且在您映射商店 ID 之后,我认为在其中收集商店 ID 也是更佳的forEach
:
const accountIds = [];
const storeIds = [];
stores.forEach((store) => {
storeIds.push(store._id);
accountIds.push(...store.members.map((m) => m.account));
});
我应该重命名memberIds
为,accountIds
因为它是帐户 ID(不是成员)的集合,它可能有点令人困惑。
推荐阅读
- javascript - 无法在 Commerce JS 上“捕获订单”
- python - 在python中解析以下文本的最佳方法是什么
- python - 如何在 PuLP (Python) 约束中调用函数?
- flutter - Flutter 桌面后台作业
- sql - 使用 Draw.io 生成 SQL/DDL 脚本?
- reactjs - reactJS 路由,错误 500 和 .htaccess:重写规则不适用于子路由
- database - 在每次提交时使用带有部署的数据库
- git - 如何同时对 repo 和子模块进行 Git 结帐?
- docker - Docker 构建命令在詹金斯中引发错误
- qaf - Qmetry - 如何更新 .wsc 文件中 api 请求键的值