I have the following schema that is used for a "Groups" collection. I want to be able to create this record and push an arbitrary number of "members" to this group when it is first created. I am unable to get the "members" field to populate when I save the record. All other fields are saved without a problem.
var groupSchema = mongoose.Schema({
creator : String,
name : String,
members: [{
type: String,
ref: 'User'
}],
created : {
type: Date,
default: Date.now
}
});
app.post('/create-group', function(req, res) {
//req.body.users = ['12345', '23456', '34567'] for example
var group = new Group({
name : req.body.group_name,
creator : req.user._id,
members: {$push: req.body.users}
});
group.save(function (err, data) {
if (!err) {
return res.json(data);
}
});
});
No results are ever stored in "members", even though all other fields are saved correctly. What am I doing wrong?
EDIT
In your schema when you wrote ref :"User" it means that you have to provide a User schema and not a string or integer. If you just want an array of string you can simply use [String].
According to the doc you have to use an objectID http://mongoosejs.com/docs/populate.html
members: [{ type: Schema.Types.ObjectId, ref: 'User' }]
In the link provided above you will be able to check how to save your group and adding an arbitrary number of members.
members: [{ type: Schema.Types.ObjectId, ref: 'User' }]
As Su4p has pointed out. Don't worry about req.body.users containing strings instead of ObjectIds. mongoose will cast the strings into objectIDs.
There's also another mistake,
members: {$push: req.body.users}
should be
members: req.body.users
$push is an update operator. It's not meant for assigning arrays.