【问题标题】:Is there any way to store array of unique ids in mongoose document?有没有办法在猫鼬文档中存储唯一ID数组?
【发布时间】:2020-07-20 03:30:06
【问题描述】:

我有一个类似的 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()

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

【问题讨论】:

  • 使用addToSet而不是push
  • ObjectId() 不是对象,是 mongoDB 的 ID!

标签: javascript node.js mongoose mongoose-schema


【解决方案1】:

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

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

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

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

【讨论】:

  • 我想将 $addToSet 与文档实例一起使用。原来有一个方法 docInstance.updateOne();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-10
  • 1970-01-01
  • 2014-01-29
  • 2012-07-31
  • 2018-07-11
  • 2022-12-09
相关资源
最近更新 更多