繁体   English   中英

有没有办法在 mongoose 文档中存储唯一 ID 数组?

[英]Is there any way to store array of unique ids in mongoose document?

我有一个 userSchema 像:

let userSchema = new Schema({
    // others
    followers: [{type: SchemaTypes.ObjectId, ref: "user"}]
})

现在我如何添加关注者,以便它每次都是独一无二的并提供良好的性能。 我试过这个

user.followers.push(anotherUserId);
user.followers = Array.from(new Set(user.followers));
user.save()

但它不会唯一地存储它们。 它存储 object,因此该设置不起作用。 有没有办法在不迭代每一个的情况下做到这一点? 如果用户有数百万的追随者,那么迭代显然会很慢。

如前所述,您应该使用 updateOne 来执行此操作...

await UserSchema.updateOne({
        _id: userId,
    },{
        $addToSet: {
            followers: idToAdd
        }
    }
).lean();

如前所述,您必须使用 _id 作为字符串...

$addToSet 仅当他不在数组中时才会添加关注者 ID,相反 $push 无论如何都会添加它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM