使用猫鼬检索数组中的对象信息
Posted
技术标签:
【中文标题】使用猫鼬检索数组中的对象信息【英文标题】:Retrieve object information within an array with mongoose 【发布时间】:2021-10-28 11:04:59 【问题描述】:我正在使用 node、express、typescript 和 mongoose 制作 API Rest。我有一个方法 GET 可以返回这个结果:
"success": true,
"status": 200,
"message": "categories listed",
"data": [
"_id": "612650e55fe1ce0de138e2af",
"products": [
"_id": "612650e55fe1ce0de138e2b0",
"productID":
"reviews": [
"611e61ba8cb43f7454787ebb",
"611e62008cb43f7454787ebc"
],
"_id": "610b18f3e2244a187b36f2d7",
"title": "PS4",
"description": "La mejor consola del mercado del mundo, mundial",
"photo": "https://amazon-clone-jparrot.s3.amazonaws.com/1628123519052",
"price": 400,
"stockQuantity": 23,
"__v": 0,
"category": "60fc6454b68717acc239cc6a",
"owner": "610b9ed8763da4308223aae0",
"averageRating": null,
"id": "610b18f3e2244a187b36f2d7"
,
"quantity": 1,
"price": 400
],
"owner":
"_id": "611d2d39dfcc705972c1ccb8",
"name": "Jaume",
"email": "jaumeparrot2@gmail.com",
"password": "$2a$10$Rv9Rzrff6578feCdDjyeKuarKCSHYRqKp5n5wTi2IWtcLBOupvPgu",
"__v": 0,
"address": "611e9ccdf47c7a7a9cb1d5d9"
,
"estimatedDelivery": "Wednesday September 1st",
"__v": 0
]
问题是我需要检索对象“owner”,也就是我需要恢复这个json:
"success": true,
"status": 200,
"message": "categories listed",
"data": [
"_id": "612650e55fe1ce0de138e2af",
"products": [
"_id": "612650e55fe1ce0de138e2b0",
"productID":
"reviews": [
"611e61ba8cb43f7454787ebb",
"611e62008cb43f7454787ebc"
],
"_id": "610b18f3e2244a187b36f2d7",
"title": "PS4",
"description": "La mejor consola del mercado del mundo, mundial",
"photo": "https://amazon-clone-jparrot.s3.amazonaws.com/1628123519052",
"price": 400,
"stockQuantity": 23,
"__v": 0,
"category": "60fc6454b68717acc239cc6a",
"owner":
"_id": "611d2d39dfcc705972c1ccb8",
"name": "Jaume",
"about": "My na is Jaume",
"__v": 0
,
"averageRating": null,
"id": "610b18f3e2244a187b36f2d7"
,
"quantity": 1,
"price": 400
],
"owner":
"_id": "611d2d39dfcc705972c1ccb8",
"name": "Jaume",
"email": "jaumeparrot2@gmail.com",
"password": "$2a$10$Rv9Rzrff6578feCdDjyeKuarKCSHYRqKp5n5wTi2IWtcLBOupvPgu",
"__v": 0,
"address": "611e9ccdf47c7a7a9cb1d5d9"
,
"estimatedDelivery": "Wednesday September 1st",
"__v": 0
]
为了生成这个 JSON,我使用了这个方法: https://github.com/jparrot92/amazon-clone-back/blob/master/src/controllers/order.ts
【问题讨论】:
你期望的输出是什么? 你能展示你的代码吗? 我的代码在这里:github.com/jparrot92/amazon-clone-back/blob/master/src/… 【参考方案1】:这是解决方案:
const products = await Order.find( owner: req.user._id )
.populate('owner')
.populate(
path: 'products.productID',
populate:
path: 'owner',
model: 'Owner',
,
)
.exec();
【讨论】:
【参考方案2】:要检索您应该使用data.owner
。这会将owner
详细信息作为对象。
【讨论】:
以上是关于使用猫鼬检索数组中的对象信息的主要内容,如果未能解决你的问题,请参考以下文章