Reputation: 2178
I've got a big problem, i'm trying to use model associations in Mongoose because it would be really useful but there's something i don't get ...
Let's say there's a User model with a schema like ... (among others)
user_geos : [{
type: Mongo.Schema.ObjectId,
ref: 'UserGeo',
}]
And there's a UserGeo model with this schema ... (among others)
_user: {
type: Mongo.Schema.ObjectId,
ref: 'User'
}
Very simple, when I'm creating a new UserGeo, it should automatically add it to the user_geos array within User, right ?
user_geo_infos._user = user.id;
db.UserGeo.create(user_geo_infos, function(error, user_geo) {
catches.error(error);
console.log(user_geo);
});
The big problem I got is when i'm creating it, it fills correctly the "_user" field in UserGeo in the database but the User model doesn't fill itself. The array stay empty ("[]"). A detail but you really understood is UserGeo got one User and User got many UserGeo.
I'm really stuck, did i do something wrong ? I checked everywhere and read the Mongoose documentation like 10 times now ...
Any idea ? Thanks people ;)
Upvotes: 1
Views: 130
Reputation: 2178
Ok I tried to make it manually and it works but i'm quite disappointed ... Looks like this ...
db.UserGeo.create(user_geo_infos, function(error, user_geo) {
db.User.findOne(user.id, function(error, user) {
catches.error(error);
user.user_geos.push(user_geo.id);
user.save();
});
catches.error(error);
console.log(user_geo);
});
After I create a UserGeo I get the User and then push the new data to the User field ...
This is solution is heavy, maybe make some helpers would make it lighter .. Thanks anyway :)
Upvotes: 0
Reputation: 146134
Very simple, when I'm creating a new UserGeo, it should automatically add it to the user_geos array within User, right ?
Nope. There is a lot less magic/automatic stuff here than you are hoping for. Mongodb, as well as mongoose, will only ever act upon a single collection at a time. This will do the querying automatically when you load records and use the mongoose .populate
helper, but it doesn't help you writing across collections.
Upvotes: 4