简体   繁体   中英

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

I have a userSchema like:

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

now how do I add followers so that it is unique every time and gives good performance. I tried this

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

but it doesn't store them uniquely. It stores object so the set does not work. Is there any way to do it without iterating over every one of them? If the user has millions of followers then iterating is obviously going to be slow.

As said you should use updateOne to do this...

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

And as mentioned you have to use the _id as a string...

$addToSet will add the follower ID only if he was not in the array, on the opposit $push would add it anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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