Search code examples
node.jsmongodbexpressmongoskin

Finding a MongoDB document by different types with Mongoskin


This is an example of document that I have in my MongoDB:

{
    "_id": ObjectId('5525039895884d66710d0fc3'),
    "prid": "63527",
    "data": {
        "sku": "HF22-81639",
        "name": "Product Test",
        "ean": "8763900872512",
        "description": "This product is my first test",
    }
}

I want to make several search methods, where the search criteria are search by SKU, EAN or PRID. I created the methods but do not work, this is the example of one of the methods that I created and it does not work, just find the first document of my database but without any search criteria.

This search for "_id" if it works perfectly:

// GET - "_id"
app.get("/:id", function(req, res, next) {
    req.collection.findOne({
        _id: id(req.params.id)
    }, function(e, result) {
        if(e) return next(e);
        res.send(result);
    });
});

This search for "sku" does not work (this is where I need help):

// GET - "sku"
app.get("/sku/:id", function(req, res, next) {
    req.collection.findOne({
        sku: id(req.params.sku)
    }, function(e, result) {
        if(e) return next(e);
        res.send(result);
    });
});

Solution

  • Not sure how your id() function is defined but you could try:

    // GET - "sku"
    app.get("/sku/:id", function(req, res, next) {
        req.collection.findOne({
            "data.sku": req.params.id
        }, function(e, result) {
            if(e) return next(e);
            res.send(result);
        });
    });
    

    In your original code, req.params.sku is undefined because the req.params object doesn't have the field sku. From the url, only the req.param.id field is defined (from this => "/sku/:id"). So for example, if you test your API with this url:

    http://localhost:3000/sku/HF22-81639
    

    will bring back the document:

    {
        "_id": ObjectId('5525039895884d66710d0fc3'),
        "prid": "63527",
        "data": {
            "sku": "HF22-81639",
            "name": "Product Test",
            "ean": "8763900872512",
            "description": "This product is my first test",
        }
    }