查询一个对象数组并返回一个对象 - mongodb

问题描述 投票:0回答:1

我在我的模型中搜索一个目前包含虚拟帖子的数组时遇到了一些麻烦。

我的帖子数组看起来像这样

posts: [
  {
    image: <filename>,
    comments: [],
    joined: <number>,
  }
]

posts数组atm包含大约10个对象。我需要一种方法来查询这个数组并返回一个对象。我已经尝试过在其他类似问题上给出的答案,但它们都返回了整个用户,这不是我想要的。

我试过这个:

model
  .find(
    { $match : { "posts.image": req.params.image } },
    { $unwind : "$posts" },
    { $match : { "posts.image": req.params.image } }
   )

这也返回整个对象,包括密码,用户名等。我也尝试过$elemMatch,没有运气。

我只期望它返回一个对象(不是多个对象),因为生病了用req.params查询数组。

javascript node.js mongodb mongoose nested
1个回答
0
投票

不确定不完全确定这是否是您要求的,但是获取数组的单个属性值的方法将以这种方式完成

如果我被误解,请澄清你的意思,我会修改我的答案。

var posts = [{
            image: "x.jpg",
            comments: [],
            joined: 12
           },
           {
            image: "x1.jpg",
            comments: [],
            joined: 121
           },
           {
            image: "ax.jpg",
            comments: [],
            joined: 2
           }
           ];

for (a = 0; a < posts.length; a++){
  console.log(posts[a].image);
}
© www.soinside.com 2019 - 2024. All rights reserved.