首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在mongo中删除选中的文档数组

如何在mongo中删除选中的文档数组
EN

Stack Overflow用户
提问于 2020-11-27 14:28:26
回答 1查看 24关注 0票数 0

我不得不找到商店来从他们的会员中删除他们的is,所以我选择了他们,我猜对我的代码deleteMany.here使用相同的查询不是一个好主意:

代码语言:javascript
复制
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的新手,请随时改进我的代码。

代码语言:javascript
复制
// 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" }],
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-27 15:16:23

我认为你的代码几乎没问题,在你从账户中取出商店I后,你应该删除Stores by I:

代码语言:javascript
复制
await Store.deleteMany({ _id: { $in: storeIds } })

正如我所看到的,您使用的是Mongoose,所以您应该在代码中使用_id,而不是id。如果你的代码没有从账户中删除store引用,我想这就是为什么。

在您的代码中,您有一个针对商店的forEach来收集会员it,在映射商店it之后,我认为在该forEach中收集商店it也是更理想的做法:

代码语言:javascript
复制
const accountIds = [];
const storeIds = [];

stores.forEach((store) => {
  storeIds.push(store._id);
  accountIds.push(...store.members.map((m) => m.account));
});

我应该将memberIds重命名为accountIds,因为它是帐户ids (而不是成员)的集合,这可能会有点混乱。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65032939

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档