簡體   English   中英

查詢對象數組並返回單個對象-mongodb

[英]query an array of objects and return a single object - mongodb

我在搜索模型中存在的數組時遇到了麻煩,該數組當前包含虛擬帖子。

我的帖子數組看起來像這樣

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查詢數組。

不確定不確定是否要這樣做,但是可以通過這種方式來獲取數組的單個屬性值

如果我被誤解了,請說明您的要求,然后我將修改答案。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM