查找与node.js mongodb

时间:2017-03-28 09:43:24

标签: node.js mongoose

我目前的模式如下:

var User = new Schema({
    id: String,
    firstName: String,
    lastName: String,
    password: String,
    username: String,
    position: [{
          title: String,
          location: String,
          start: String,
          term:Number,
          description:String,
                    date: {type: Date, default: Date.now}
  }]

});

我有两个用户,每个用户都有两个嵌入式位置文档。

user1:

"position" : [ 
    {
        "title" : "Business Analyst",
        "location" : "Dublin",
        "start" : "May 2017",
        "term" : 6,
        "description" : " Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis erat vitae dsit amet, consectetur adipiscing elit. Vivamus quis erat vitae dolor tempus euismod non in mi",
        "_id" : ObjectId("58d6b7e11e793c9a506ffe0f")
    }, 
    {
        "description" : "description",
        "term" : 12,
        "start" : "may 2018",
        "location" : "Dublin",
        "title" : "Web Developer",
        "_id" : ObjectId("58d6af99e4318f4703ceb2af")
    }
],

用户2:

"position" : [ 
    {
        "title" : "Software Engineer",
        "location" : "Cork",
        "start" : "May 2017",
        "term" : 9,
        "description" : " Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis erat vitae dolor tempus euismod non in miorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis erat vitae dolor tempus euismod non in mi"

    }, 
    {
        "title" : "Web Developer",
        "location" : "Waterford",
        "start" : "May 2017",
        "term" : 6,
        "description" : " Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis erat vitae dsit amet, consectetur adipiscing elit. Vivamus quis erat vitae dolor tempus euismod non in mi"
    }
],

但是,如果我搜索“Web Developer”,我似乎只能返回第一个用户(我理解整个文档返回的原因)但是我可以进行搜索并获取与字符串'Web匹配的所有子文档开发者? 我正在使用Ajax,我的帖子查询如下:

    app.post('/search', function (req, res) {

  User.find({'position.title':req.body.position}).exec(function (err, result) {
    res.send({ results: result });
});
});

退回的对象:

enter image description here

1 个答案:

答案 0 :(得分:1)

为了仅返回子文档,您必须将该字段作为第二个参数传递给.find函数。

var position = new RegExp(req.body.position, 'i');

User.find({'position.title': position}, 'position.$')
.exec(function (err, result) {
});