node.js - 变量替换在带有 Node js的mongodb中的$in中不起作用

标签 node.js mongodb express

我已将 Node 路径构造为 /57639afa5961debc1b256745/,/5763c5d17d05688c1838c7a3/, 但当我尝试用 nodepath 替换时,它得到的结果为空数组,即使它有 child :

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);
                }               
            });
    }); 
};

最佳答案

您需要将 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) => {...

关于node.js - 变量替换在带有 Node js的mongodb中的$in中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37880338/

相关文章:

node.js - 如何在 Windows 上运行 npx Node.Js 命令

node.js - 在 Joi 中返回多个错误

mongodb - $sum mongodb 中具有相同 id 的数组

mysql - 我如何在我的 postman 中产生多个错误消息

html - 通过 Nodejs 中间件路由某些请求子集时 HTML 中的相对 URL

Node.js Express

javascript - flickr node.js api 上传照片

MongoDB 用户未被授权

python - 如何为 python 单元测试模拟 mongodb?

node.js - Tedious.js 不支持的协议(protocol)