简体   繁体   中英

Update a document collection in MongoDB using Node.js

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.

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}})

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