How to update Reference Array in mongoose

8.6k Views Asked by At

I have a Group Collection, which is having a Reference array of Members. Two Objects are inter-connected like follow. When I am adding new members to the group the members field of Group object needed to be updated. How can I do this with a mongoose update operator.

var MemberSchema = new Schema({
    name:{
        type:String,
        default:null
    },
    user_id:{
        type : Schema.ObjectId,
        ref : 'User',
        default : null
    }
});

var GroupSchema = new Schema({
    name:{
        type:String,
        default:null
    },
    description:{
        type:String,
        default:null
    },
    members:[MemberSchema],

},{collection:"groups"});

Thank You in advance.

Update

I added a sample document of group.

{
    "_id" : ObjectId("586a2e694467c41218b302c3"),
    "members" : [ 
        {
            "_id" : ObjectId("586a2e694467c41218b302c6"),
            "user_id" : ObjectId("58171d75e72bf516f92dcd4e"),
            "name" : "Lakmal Kapukotuwa"
        }, 
        {
            "_id" : ObjectId("586a2e694467c41218b302c5"),
            "user_id" : ObjectId("5821807516325e127f59438e"),
            "name" : "Prasad Perera"
        }, 
        {
            "_id" : ObjectId("586a2e694467c41218b302c4"),
            "user_id" : ObjectId("586263515356e908de6c899a"),
            "name" : "Sadun Prasad"
        }
    ],
    "description" : "Des 1",
    "name" : "My group",
    "__v" : 0
}
2

There are 2 best solutions below

0
On BEST ANSWER

If you are sending the new members as a list of objects with the following structure e.g.

membersListToAdd = [ 
    {
        "user_id": "58171d75e72bf516f92dcd4e",
        "name": "foo"
    }, 
    {
        "user_id": "5821807516325e127f59438e",
        "name": "bar"
    }
]

then use $push with $each modifier in an update as follows:

var query = { name: 'My Group' },
    options = {},
    callback = function (err, result) { console.log(result); };
Group.update(query, { $push: { members: { $each: membersListToAdd } } }, options, callback)
2
On

You are doing this wrong,

no need to have links in both collections and no need to nest models

try this instead

var Group = mongoose.model("Group", new Schema({
    name: {
        type:String
    },
    description: {
        type:String
    },
}));

Group.virtual("users", {
    ref: "User",
    localField: "_id",
    foreignField: "groups"
});

var User =  mongoose.model("User", new Schema({
    name:{
        type:String
    },
    groups: [{
        type : Schema.ObjectId,
        ref : 'Group'
    }]
}));