0

i have two schemas

var UserSchema  =new mongoose.Schema({
    username:String,
    password:String,
    user_email:String,
    user_contacts:[
        {
            type:mongoose.Schema.Types.ObjectId,
            ref:"User"
        }
    ]
})
module.exports=mongoose.model("User",UserSchema);

and

var friendRequestSchema=new mongoose.Schema({
    requester:{
        type:mongoose.Schema.Types.ObjectId,
        ref:"User"
    },
    recipient:{
        type:mongoose.Schema.Types.ObjectId,
        ref:"User"
    },
    //1 for requested , 2 for accepted , 3 for rejected
    status:Number
});
module.exports=mongoose.model("FriendRequest",friendRequestSchema);

and i want to find all friend requests with specific user id for requester field ,then i want to get all recipient users of these requests, and finally adding them to a dictionary where the key is the recipient user and the value is the friendRequest associated with it so i can pass it to a ejs file like this:

res.render("myrequests",{myDictionary:myDictionary});
2
  • Your question is off to a good start, but now you need to continue with "here's what I tried..." "Here's what I was expecting...", "Here's what actually happened..." It's worthwhile asking your actual question in the body of your question as opposed to just in the title, too. Commented Feb 20, 2019 at 3:42
  • thanks, i will try to do this next time Commented Feb 22, 2019 at 0:05

1 Answer 1

2

you can now do it in Mongo 3.2 using $lookup

$lookup takes four arguments

from: Specifies the collection in the same database to perform the join with. The from collection cannot be sharded.

localField: Specifies the field from the documents input to the $lookup stage. $lookup performs an equality match on the localField to the foreignField from the documents of the from collection.

foreignField: Specifies the field from the documents in the from collection.

as: Specifies the name of the new array field to add to the input documents. The new array field contains the matching documents from the from collection.

db.Foo.aggregate(
  {$unwind: "$bars"},
  {$lookup: {
    from:"bar",
    localField: "bars",
    foreignField: "_id",
    as: "bar"

   }},
   {$match: {
    "bar.testprop": true
   }}
)

Hope this will solve your problem!!!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.