【发布时间】:2014-02-04 06:45:27
【问题描述】:
我正在节点 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 和 ads.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" }
【问题讨论】: