Henrique Henrique - 4 days ago 5
Javascript Question

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

I have a very simple one to many relationship where a

User
has a list of
Alerts
. 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
Alert
and adds it to an existing
User
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.alerts.push(alert);
user.save(function(error) {
console.log("saved");
});
});
});
}


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

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

Try this instead:

user.alerts.push(alert.id);

or

user.alerts.push(alert._id);

both are correct.

Comments