Query an entire Array of objects in MongoDB

I'm building my first NodeJS application and have hit a dead end with a query I'm trying to create.

const userSchema = new Schema({
    email:{
       type: String,
    },
    friends: [{
       name: String,
    }],
    name: {
       type: String,
    }
});

My goal is to retrieve every single name from each object in the friends array, and display them to the user.

I have tried: (And many more)

 const friendNames = await User.find( 
    {_id: req.user._id},
    { friends: { name: String } }
)


const friendNames = await User.find( 
    {_id: req.user._id},
    { friends: { $elemMatch: { name: String } }}
)


 const friendNames = await User.find( 
    {_id: req.user._id},
    { friends: { name: {$exists : true} } }
)

I thought this would be a pretty simple query, but I either overlooked something or I'm misunderstanding a concept entirely. This is my first major roadblock. Any help or guidance would be greatly appreciated.

1 answer

  • answered 2018-02-13 02:20 Nick

    Just a find({ _id: req.user._id }, { friends: 1 }) should do it. This is using projection.