简体   繁体   中英

Posting Schema.Types.ObjectId arrays to MongoDB

How can I post an array of Schema.Types.ObjectId (s) to MongoDB? I'm trying to create User Groups, which is a group of the 'User' Model eg

var UserGroup = new Schema({
    users: [{
        type: Schema.Types.ObjectId,
        ref: 'User'
    }]
});

New UserGroup Function

module.exports.create = function(request, response) {
    var group = new UserGroup({
        users = request.body.users
    });

    group.save(function(error) {
        if(error) { throw error; } else { response.send('Group Created Successfully.');
    });
};

I'm currently using Postman to test the functionality, how exactly should the data be posted?

As a Javascript array ie ['A_USER_ID', 'A_USER_ID'] ?

Thanks!

@Answer

I was using the older syntax of the select() function, and therefore was passing invalid parameters to the $push function. When sending the request, I simply pass the ObjectIds as id,id,id and once they get to the server, simply put it into an array using var my_array = request.body.users.split(','); and then push it to the database using the following:

$push: { users: { $each: my_array } }

I hope this was helpful, the documentation isn't particularly clear on this matter.

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