如何在子文档中搜索

时间:2015-11-07 11:08:47

标签: node.js mongodb mongoose

我有一个angular-fullstack应用程序,由angular-fullstack yeoman生成器生成,我有一个查询模型如下:

'use strict';

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

/**
 * Discussion Question Schema
 */
var QuerySchema = new Schema({
    date: {
        type: Date,
        default: Date
    },
    tags: [{
        type: Schema.ObjectId,
        ref: 'Tag'
    }]
});

module.exports = mongoose.model('Query',  QuerySchema);
var deepPopulate = require('mongoose-deep-populate')(mongoose);

Tag有一个字段text。现在在我的查询控制器中,我必须深入填充其他一些字段并对它们进行分页,所以我在控制器函数中尝试这样的事情:

exports.index = function(req, res) {
    var escapeRegExpChars = function (text) {
        return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    };
    require('paginate-for-mongoose');
    var limit,page;
    if(req.query.limit != undefined) limit = req.query.limit;
    else limit = 10;
    if(req.query.page != undefined) page = req.query.page;
    else page = 1;
    var queryObj = {};
    if(req.query.searchText != undefined && req.query.searchText != '')
        queryObj['title']= new RegExp(escapeRegExpChars(req.query.searchText), 'i');
    var options = {
        perPage:limit,
        delta:2,
        page:page
    };
    if(req.query.fold !=undefined && req.query.fold != '') queryObj["tags.text"] = req.query.fold;
    var query = Query.find(queryObj).populate('tags','text').deepPopulate('user class user.class');
    query.paginate(options,function(err, resp){
        if(err) { return handleError(res, err); }
        if(req.query.fold) console.log(resp.results);
        return res.status(200).json(resp.results);
    });
};

如何搜索tags.text值与req.query.fold值完全匹配的查询?

1 个答案:

答案 0 :(得分:0)

MongoDB不支持联接,因此要搜索链接的文档,您必须分两步执行:

// First look up the _id of the tag
Tags.findOne({text: req.query.fold}, function(err, tag) {
    if (tag) {
        // Add a match in the doc's tags array to the tag's _id
        queryObj.tags = tag._id;
        var query = Query.find(queryObj)... 
        ...
    }
});