【问题标题】:UnExpected output from mongoDB来自 mongoDB 的意外输出
【发布时间】:2017-02-14 13:50:49
【问题描述】:

我正在使用 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 变量解决这个问题。

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

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

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

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

    set SAMPLE_SIZE=1&& node example.js

    example.js

    console.log(process.env);
    

    输出:

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

    【讨论】:

    • 如果我在 npm 脚本中将它作为“start-offer-service-dev”传递:“SAMPLE_SIZE=2 node_modules/.bin/babel-node src/services/offerService/index.js”,那么是字符串还是数字?
    • 是的,我错了,通过 npm 脚本传递的参数是字符串类型,因此必须转换为 int
    猜你喜欢
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-04
    • 2018-08-21
    • 2019-12-10
    • 1970-01-01
    相关资源
    最近更新 更多