0

I am working a twitter like follow model, for which my User's schema is as follows.

var UserSchema = new Schema({ 
    username: {type: String, match: /^[a-zA-Z0-9_]+$/, unique: true}, 
    email: { type: String, unique: true }, 
    password: String, 
    followings : [{ type: ObjectId, ref: 'User' }],
    followers : [{ type: ObjectId, ref: 'User' }] });

I need to store just the user's ObjectId in the followings and followers field.

I am not sure how to Insert and Update the followings and followers collection. I tried with "Update" but it overwrites each time. Then tried push, but doesn't help.

Please help me.

Thanks in advance.

1 Answer 1

1

In your case I would use the operator $addToSet which appends a value to the array if it doesn't exist.

Example in mongodb shell

db.userSchema.update({"username" : USERNAME}, { "$addToSet" : { "followers" : ObjectId}})
Sign up to request clarification or add additional context in comments.

2 Comments

How do I remove a particular document from the collection?
try the command $pullAll. Remove all occurrences of an object from the array. Check the manual.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.