使用 Mongoskin 按不同类型查找 MongoDB 文档

Finding a MongoDB document by different types with Mongoskin

这是我 MongoDB:

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

我想做几种搜索方式,搜索条件是SKU、EAN或PRID。我创建了这些方法但不起作用,这是我创建的方法之一的示例但它不起作用,只是找到我的数据库的第一个文档但没有任何搜索条件。

搜索“_id”是否完美:

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

搜索 "sku" 无效(这是我需要帮助的地方):

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

不确定您的 id() 函数是如何定义的,但您可以尝试:

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

在您的原始代码中,req.params.sku 未定义,因为 req.params 对象没有字段 sku。从 url 开始,只定义了 req.param.id 字段(从 this => "/sku/:id")。例如,如果你用这个 url:

测试你的 API
http://localhost:3000/sku/HF22-81639

将带回文件:

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