我正在使用节点js(Modulus服务器)中的mongodb本机驱动程序。我在主文档中有子文档数组的文档结构。结构就像吼叫,
{ "adname" : "First Advertisement Image", "adsize" : "600*58", "adstatus" : "on", "modifiedAt" : "31-01-2014 05:22:26 PM", "created" : "31-01-2014 03:29:20 PM", "_id" : { "$oid" : "52eb73f8584fbf0000000001" }, "advertisements" : [{ "advname" : "diamond and jewellery", "advexpiredate" : "10-02-2014", "advduration" : "10000", "advstatus" : "on", "advshortimage" : "1391420178839-advertisement-download.jpg", "advlongimage" : "1391420179094-advertisement-bangleimages.jpg", "advid" : 1391420179600, "createdAt" : "03-02-2014 03:06:19 PM" },{ "advname" : "xyz jewellery", "advexpiredate" : "10-02-2014", "advduration" : "10000", "advstatus" : "on", "advshortimage" : "1391420178839-advertisement-download.jpg", "advlongimage" : "1391420179094-advertisement-bangleimages.jpg", "advid" : 1391420199800, "createdAt" : "03-02-2014 03:06:19 PM" } ] }
{ "adname" : "Second Advertisement", "adsize" : "260*58", "adstatus" : "on", "modifiedAt" : null, "created" : "31-01-2014 05:23:36 PM", "_id" : { "$oid" : "52eb8ec033d3510000000001" }, "advertisements" : [] }
{ "adname" : "Third Advertisement", "adsize" : "156*58", "adstatus" : "on", "modifiedAt" : null, "created" : "31-01-2014 05:24:18 PM", "_id" : { "$oid" : "52eb8eea33d3510000000002" }, "advertisements" : [] }
{ "adname" : "Fourth Advertisement", "adsize" : "250*290", "adstatus" : "on", "modifiedAt" : null, "created" : "31-01-2014 05:24:48 PM", "_id" : { "$oid" : "52eb8f0833d3510000000003" }, "advertisements" : [] }
并且我必须根据文档id从任何一个主文档中检索特定的子文档。我在节点js中使用了以下代码但是我无法按照我期望的那样进行检索。
exports.getAddsByAdvertisementId = function(id,adid,callback)
{
advertisement.find({ _id: getObjectId(id) }, { advertisements: { $elemMatch: { advid: adid } } }, function(e,adds) {
if(e) callback(e,null);
else {
adds.toArray(function(error, results) {
if(error) callback(error,null);
else callback(null,results);
});
}
});
}
例如,如果我传递_id:52eb73f8584fbf0000000001和advertisements.advid:1391420179600表示(即getAddsByAdvertisementId(52eb73f8584fbf0000000001,1391420179600) 我的结果应该是
{ "advname" : "diamond and jewellery", "advexpiredate" : "10-02-2014", "advduration" : "10000", "advstatus" : "on", "advshortimage" : "1391420178839-advertisement-download.jpg", "advlongimage" : "1391420179094-advertisement-bangleimages.jpg", "advid" : 1391420179600, "createdAt" : "03-02-2014 03:06:19 PM" }
答案 0 :(得分:0)
大概你的意思是没有得到你期望的是你没有得到一份文件。
检查您传入的值adid
是不是字符串,或将其转换为函数内的int。
此外,由于您首先使用主_id
查找文档,因此您只能得到1个结果或者没有结果。请改用findOne以避免进入只有1个项目的数组。