当前位置: 动力学知识库 > 问答 > 编程问答 >

node.js - 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 e.g.

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 i.e ['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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: