我不得不找到商店来从他们的会员中删除他们的is,所以我选择了他们,我猜对我的代码deleteMany.here使用相同的查询不是一个好主意:
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" }],
});发布于 2020-11-27 15:16:23
我认为你的代码几乎没问题,在你从账户中取出商店I后,你应该删除Stores by I:
await Store.deleteMany({ _id: { $in: storeIds } })正如我所看到的,您使用的是Mongoose,所以您应该在代码中使用_id,而不是id。如果你的代码没有从账户中删除store引用,我想这就是为什么。
在您的代码中,您有一个针对商店的forEach来收集会员it,在映射商店it之后,我认为在该forEach中收集商店it也是更理想的做法:
const accountIds = [];
const storeIds = [];
stores.forEach((store) => {
storeIds.push(store._id);
accountIds.push(...store.members.map((m) => m.account));
});我应该将memberIds重命名为accountIds,因为它是帐户ids (而不是成员)的集合,这可能会有点混乱。
https://stackoverflow.com/questions/65032939
复制相似问题