变量替换在节点js的mongo中的$ in中不起作用

时间:2016-06-17 11:23:01

标签: node.js mongodb express

我已经将节点路径构建为/57639afa5961debc1b256745/, /5763c5d17d05688c1838c7a3/,但是当我尝试用nodepath进行替换时,即使它有子节点,它也会将结果作为空数组:

Degree.prototype.findByPath = function(dbObj, degrees) {
    var nodePath = '';

    for(var i in degrees) {
        nodePath = nodePath + '/' + degrees[i]['_id'] + '/, ';
    }

    return new Promise(function (resolve, reject) {
        console.log(nodePath);
        dbObj.collection('degree').find({ 
            'path': {
                '$in': 
                    [ nodePath ] 
                } 
            }).toArray((err, results) => {
                if(err) {
                    reject(err);
                } else {
                    var nodes;

                    if(results != null)
                        nodes = degrees.concat(results);
                    else
                        nodes = degrees;

                    resolve(nodes);
                }               
            });
    }); 
};

1 个答案:

答案 0 :(得分:1)

您需要将nodePath构建为字符串数组而不是一个以逗号分隔的字符串。如果您希望将id值视为正则表达式,请使用RegExp构造函数而不是添加斜杠字符:

var nodePath = [];

for(var i in degrees) {
    nodePath.push(new RegExp(degrees[i]['_id']));
}

return new Promise(function (resolve, reject) {
    console.log(nodePath);
    dbObj.collection('degree').find({ 
        'path': {
            '$in': nodePath
            } 
        }).toArray((err, results) => {...