Home > Back-end >  Find a document by an object id in that doc in mongoDB node js express js
Find a document by an object id in that doc in mongoDB node js express js

Time:08-12

Hey this i want to fetch the products of a certain user so i added the user in the model by Object id , but when i was setting the router callBack function i didn't know how to do it !

{
    "_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"]
}

as You can see the user object id is included so how can i find it ! this i what i tried but it didn't work

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

CodePudding user response:

Solution

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

Explanation

$oid is a way to represent ObjectId in JSON. $oid is not a property that exists on the document. We need to convert the id received in request to an ObjectId and match it with the _id field of the document.

Further

Wrap the conversion into a try/catch or something similar. Converting a string to an ObjectId can fail if the string is not a proper representation of an ObjectId.

const mongo = require('mongodb');

let idAsObjectId;
try {
  idAsObjectId = mongo.ObjectId(req.params.id)
} catch (err) {
  // handle error
}
  • Related