0

I'm very new in mongoose and node js. I get some troubles in my project. here is my user model

UserSchema = new Schema({
account:String,
password:String,
display_name:String )}

and friends model

FriendSchema = new Schema({

friend_from_id:{
    type:Schema.ObjectId,
    ref:'users'
},
friend_to_id:{
    type:Schema.ObjectId,
    ref:'users'
}});

and user_status model

UserStatusSchema = new Schema({

user_id:{
    type:Schema.ObjectId,
    ref:'users'
},
status:{
    type:Boolean
},
status_text:String,
last_updated_at:String});

how can I populate or any way to make a result from friend model like this

{
"_id": "55145b6b8b9c9e6c1f739441",
"friend_to_id": {
    "_id": "5502976dbef9fa180d28ea21",
    "display_name": "Jason",
    "account": "xxx@ginmed.com",
    "status":false,
    "status::"how it's going"
},
"friend_from_id": {
    "_id": "5502976dbef9fa180d28ea21",
    "display_name": "SonPham",
    "account": "yyy@ginmed.com",
    "status":true,
    "status::"how to do it"}

this mean I want to combine both user_status and user model in a field of friend model

2 Answers2

0

I'm not quite sure I understand the question, but it appears you have a list of users for which you wish to make a self-referencing, many-to-many relationship (i.e. a user can have friends of and be a friend to many other users). To enable this, you need to update both the user object (presumably with other information) and the friends collection (with added/removed relationships). Without commenting on the solution, I think you will find what you need by looking at the "hooks" middleware (http://mongoosejs.com/docs/middleware.html) for mongoose. This allows you to execute additional functionality in the pre and post save phases. Once you've saved your user model, you can use the post save hook to update the friends model.

UserSchema.post('save', function(doc) {
    // Remove deleted friendships and add new ones here
});

As to your proposed solution, I would look at many to many relationship with nosql (mongodb and mongoose) for some possible alternatives/improvements.

Community
  • 1
  • 1
Gene
  • 534
  • 4
  • 5
0

you can use the below query to populate this two collections

FriendSchema.findOne({}).
populate(friend_from_id).
populate(friend_to_id).
exec(function (err, schema) {});