来自mongoDB

时间:2017-02-14 13:50:49

标签: node.js mongodb mongoose mongoose-schema

我正在使用mongoose来连接和查询mongoDB。

现在,如果我有以下代码:

return new Promise((resolve) => {
    mongoose.connection.db.collection('offer').aggregate([{
      $match: {
        $or: [
          {
            ccChecked: {
              $lt: new Date(currentDay + 'T00:00:00.000Z')
            }
          },
          {
            ccChecked: {
              $exists: 0
            }
          }
        ],
        _id: { $in: offerObjIds }
      }
    },
    { $sample: { size: 2 } }
    ], (err, res) => {
      console.log('res is', res);
      resolve(res);
    });
  });

提供的结果很好,我们得到了预期的输出。 但是如果我们有以下查询,并且我将SAMPLE_SIZE提供为2:

const sampleSize = process.env.SAMPLE_SIZE
  return new Promise((resolve) => {
    mongoose.connection.db.collection('offer').aggregate([{
      $match: {
        $or: [
          {
            ccChecked: {
              $lt: new Date(currentDay + 'T00:00:00.000Z')
            }
          },
          {
            ccChecked: {
              $exists: 0
            }
          }
        ],
        _id: { $in: offerObjIds }
      }
    },
    { $sample: { size: sampleSize } }
    ], (err, res) => {
      console.log('res is', res);
      resolve(res);
    });
  });

在这种情况下,我得到的结果是未定义的。有人可以解释为什么会出现这种行为以及如何通过process.env变量来解决这个问题。

1 个答案:

答案 0 :(得分:0)

验证sampleSize是否为整数。它可能是来自process.env变量的字符串。

{ $sample: { size: <positive integer> } }

更新: 我在命令行上测试了一个脚本。查看结果:

set SAMPLE_SIZE=1&& node example.js

example.js

console.log(process.env);

输出:

  

{... SAMPLE_SIZE:'1',...}