[英]How do I retrieve data from an array, to an object in Mongodb?
我想檢索filename
和path
數據,如何獲取這些數據? 這里我使用“貓鼬”:“^ 5.11.15”,
文件:
{
....,
....,
avatar : [
{
original: {
filename: asdas.jpg,
path: /images/user/1231231/asdas.jpg,
},
},
.......: {
.....,
.....,
}
.......: {
.....,
.....,
}
],
....,
....,
}
我試過這樣的腳本,但還是不想輸入我想要的數據。
腳本:
const users = await User.findById(req.user.id).select("avatar.original.path");
console.log(users);
控制台日志結果:
{ avatar: [ { original: [Object] } ], _id: 6085afb36c3e012d48f7e1f1 }
對於這樣的檢索所需的結果
字符串中所需的 output:
/images/user/1231231/asdas.jpg
請幫助大家
您不能在 find 方法中直接訪問數組中的屬性,
嘗試從 MongoDB 4.4 開始的聚合算子,
$arrayElemAt
從數組中獲取第一個元素const users = await User.findById(req.user.id)
.select({
_id: 0,
path: { $arrayElemAt: ["$avatar.original.path", 0] }
}).lean();
console.log(users.path);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.