用Mongoskin查找不同types的MongoDB文档
这是我在MongoDB中的一个文档示例:
{ "_id": ObjectId('5525039895884d66710d0fc3'), "prid": "63527", "data": { "sku": "HF22-81639", "name": "Product Test", "ean": "8763900872512", "description": "This product is my first test", } }
我想制作几种search方法,其中search条件是通过SKU,EAN或PRID进行search。 我创build的方法,但不工作,这是我创build的方法之一的例子,它不工作,只是find我的数据库的第一个文件,但没有任何search条件。
这个search“_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); }); });
search“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"
)。 举个例子,如果你用这个URLtesting你的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", } }