首页 > 解决方案 > 如何在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" }],
});

标签: node.jsmongodbmongoose

解决方案


我认为您的代码几乎可以,在您从 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(不是成员)的集合,它可能有点令人困惑。


推荐阅读