在mongoDBNode js-express js中,通过该文档中的对象id查找文档



嘿,我想获取某个用户的产品,所以我按对象id在模型中添加了该用户,但当我设置路由器回调函数时,我不知道该怎么做!

{
"_id": {
"$oid": "62f250d3e2533cf4ca2ad7f3"
},
"image": "https://eshop-server.herokuapp.com/public/uploads/Surface-Pro-7-128GB-1604665289664.png",
"brand": "ASUS",
"price": {
"$numberInt": "250"
},
"rating": null,
"numReviews": null,
"isFeatured": false,
"name": "Surface Pro 7 128GB",
"description": "Tablet PC - Intel Core i3 1005G1 Ice Lake, touchscreen 12.3" IPS 2736 × 1824, RAM 4GB LPDDR4X, Intel UHD Graphics",
"category": {
"$oid": "5f15d54cf3a046427a1c26e3"
},
"user": {
"$oid": "62f0e99be78e33cc5662d1f4"
},
"reviews": [{
"avatar": "https://pbs.twimg.com/profile_images/1760228143/Vetor-Johnny-Bravo-Vetorizado-Corel_400x400.jpg",
"name": "Johnny Bravo",
"review": "Amazing experience all around"
}, {
"avatar": "https://vignette.wikia.nocookie.net/asterix/images/3/3c/Asterix.png",
"name": "Asterix",
"review": "It's very hard. Only managed with resource to magic potion"
}, {
"avatar": "https://vignette.wikia.nocookie.net/looneytunes/images/7/7f/Coyote.gif",
"name": "Wild Coyote",
"review": "All my trickery and tools paid of. Thank ACME for suggesting this product to me"
}],
"countInStock": {
"$numberInt": "8"
},
"__v": {
"$numberInt": "0"
},
"richDescription": "eatures a detachable keyboard and offers the comfort of a classic laptop as well as the convenience of a tablet.&nbsp",
"images": ["http://localhost:3000/public/uploads/5f15d8852a025143f9593a7c-1604665316399.png", "http://localhost:3000/public/uploads/5f15d8852a025143f9593a7c-1604665316400.jpeg"]
}

正如你可以看到的用户对象id包括在内,所以我怎么能找到它!这是我尝试过的,但它不起作用

router.get(`/:id/products`, async (req, res) => {
const productList= await Product.find({user.$oid:req.params.id}).populate("user");
if (!productList) {
res.status(500).json({ success: false });
}
res.send(productList);
});

解决方案

Product.find({user._id: mongo.ObjectId(req.params.id)})替换Product.find({user.$oid:req.params.id})

解释

$oid是在JSON中表示ObjectId的一种方式。$oid不是文档中存在的属性。我们需要将请求中收到的id转换为ObjectId,并将其与文档的_id字段匹配。

进一步

将转换包装成try/catch或类似的内容。如果字符串不是ObjectId的正确表示形式,则将字符串转换为ObjectId可能会失败。

const mongo = require('mongodb');
let idAsObjectId;
try {
idAsObjectId = mongo.ObjectId(req.params.id)
} catch (err) {
// handle error
}

相关内容

  • 没有找到相关文章

最新更新