使用Mongoose通过id查找subdoc

时间:2017-03-27 23:49:08

标签: node.js mongodb mongoose

我正在尝试使用mongoose和mongdb查找和更新子文件,但我似乎无法使用ID找到子文件。

我的架构

var Attending = new Schema({
   users: []
});

var Query = new Schema({
   name: [],
   url: [],
   attending: [Attending],
   img: []
});

对两个文档使用ID,只需查找文档的返回null即可。但是,如果我只使用一般Id我可以找到整个doc但不能找到subdoc。

 Queries.findOne(
     { "_id": queryId, "attending._id": attendingId },
      function(err, doc) {
        if (err) throw err;
        console.log(doc);
        res.render('index');
     }
 );

示例文档

{
"_id": {
    "$oid": "58d995026d7c8f0a3028a50f"
},
"img": [
    "https://pic1",
    "https://pic2"
],
"attending": [
    {
        "_id": {
            "$oid": "58d995026d7c8f0a3028a505"
        },
        "users": [
            "somebody"
        ]
    },
    {
        "_id": {
            "$oid": "58d995026d7c8f0a3028a506"
        },
        "users": [
            "another person"
        ]
    }
],
"url": [
    "https://www.yelp.com/2",
    "https://www.yelp.com/1"

],
"name": [
    "The Rivermill",
    "Sharkeys"
],
"__v": 0
}

我正在使用正确的ID并期望返回的第一个子目录或者搜索到的任何一个。而是返回null

查询是这样的:

var names = [];
var urls = [];
var imgUrls = [];
var attendingArray = [];

for (var i=0; i<10; i++) {
    names.push(businesses[i].name);
    urls.push(businesses[i].url);
    imgUrls.push(businesses[i].image_url);

    //add attending schema
    var newAttending = Attending({
          users: ["somebody"]
    });

   attendingArray.push(newAttending);
} 

var newQuery = Queries({
        name: names,
        url: urls,
        attending: attendingArray,
        img: imgUrls
});    

0 个答案:

没有答案