简体   繁体   English

查询MongoDB中的整个对象数组

[英]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. 我正在构建我的第一个NodeJS应用程序,但由于尝试创建的查询而陷入僵局。

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. 我的目标是从friends数组中的每个对象中检索每个名称,并将其显示给用户。

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. 任何帮助或指导将不胜感激。

Just a find({ _id: req.user._id }, { friends: 1 }) should do it. 只需一个find({ _id: req.user._id }, { friends: 1 }) This is using projection . 这是使用投影

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM