Henrique Henrique - 1 year ago 71
Javascript Question

Storing a one to many relationship in Node.js using Mongoose

I have a very simple one to many relationship where a

has a list of
. For this, I've defined the following schemas:

var userSchema = new Schema({
email: String,
alerts: [{type: Schema.Types.ObjectId, ref: 'Alert'}]
var User = mongoose.model('User', userSchema);

var alertSchema = new Schema({
_creator: {type: Schema.Types.ObjectId, ref: 'User'},
value: String,
var Alert = mongoose.model('Alert', alertSchema);

Now, I'm trying to create a function which creates a new
and adds it to an existing
from the database. I have the following code (removing error-handling so the code is shorter):

function createAlertForUser(userId, value) {
User.findOne({_id: userId}, function (error, user) {

var alert = new Alert({
_creator: userId,
value: value

alert.save(function (error, alert) {

// push it to the user
user.save(function(error) {

However, when I check the database, I seem to be saving null values to the User's list of alerts. Any ideas what I'm missing?

Answer Source

You try to push a whole Alert object to an array of ObjectId.

Try this instead:




both are correct.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download