【问题标题】:Query an entire Array of objects in MongoDB在 MongoDB 中查询整个对象数组
【发布时间】:2018-07-23 07:57:36
【问题描述】:

我正在构建我的第一个 NodeJS 应用程序,但我尝试创建的查询遇到了死胡同。

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

我的目标是从朋友数组中的每个对象中检索每个名称,并将它们显示给用户。

我已经尝试过:(还有更多)

 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} } }
)

我认为这将是一个非常简单的查询,但我要么忽略了某些东西,要么完全误解了一个概念。这是我的第一个主要障碍。任何帮助或指导将不胜感激。

【问题讨论】:

  • 类似const friendNames = await User.find( {_id: req.user._id}, { friends:1 } )

标签: arrays node.js mongodb mongodb-query


【解决方案1】:

只需find({ _id: req.user._id }, { friends: 1 }) 即可。这是使用projection

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 2012-05-05
    • 2014-05-13
    • 1970-01-01
    • 2020-03-28
    相关资源
    最近更新 更多