【问题标题】:Mongoose .select is not a function when using with Azure Function与 Azure 函数一起使用时,Mongoose .select 不是函数
【发布时间】:2020-03-16 17:01:25
【问题描述】:

我正在尝试将 mongoose .select 运算符与我的 azure 函数一起使用,但它一直在说 TypeError: db.collection(...).findOne(...).select is not a function at db.collection.find.toArray 它在控制台中返回用户的数据,但不使用.select 过滤它 这是为什么呢?

var MongoClient = require('mongodb').MongoClient;
var Post = require('./model/post');
var mongoose = require('mongoose');
module.exports = async function (context, req) {

  let currentPage = 1;


  MongoClient.connect(process.env.CosmosDBConnectionString, async (err, client) => {




    let send = response(client, context);

    if (err) send(500, err.message);

    let db = client.db(process.env.dbName);


    await db.collection('listings').find(
      {
        $and: [
          { winnerHasBeenNotified: false },
          { auctionEndDateTime: { $lte: Date.now().toString() } }
        ]
      }
    )

      .toArray((err, result) => {
        console.log("result");
        console.log(result);


        if (result) {

          for (let i = 0; i < result.length; i++) {

            db.collection('users').findOne(
              {

                _id: mongoose.Types.ObjectId(result[i].bidderId)

              }
            ).select("notificationBy").toArray((err, result) => {
              console.log("USER RESULT!");
              console.log(result);
            });


          }


        }




        if (err) send(500, err.message);
        send(200, JSON.parse(JSON.stringify(result)));



      });
  });




};

function response(client, context) {
  return function (status, body) {
    context.res = {
      status: status,
      body: body
    };

    client.close();
    context.done();
  };
}

【问题讨论】:

    标签: node.js mongodb azure mongoose azure-functions


    【解决方案1】:

    find() 返回一个游标,它有一个select 方法。 findOne() 检索单个文档并在未提供回调时返回一个承诺。

    如果您只想获取“notificationBy”字段,请尝试将 fields 选项传递给 findOne。

    【讨论】:

    • 一次可能有超过 1 个获胜者返回。我们的想法是每 10 分钟执行一个计时器 azure 函数,获取所有返回 winnerHasBeenNotified = false 的获胜者。然后我将向这些用户发送一封电子邮件,并将 DB 中的值更新为 true。当您说字段选项时,我对您的意思感到有些困惑。你能举个例子吗?
    猜你喜欢
    • 2017-04-21
    • 2017-07-20
    • 1970-01-01
    • 2020-12-10
    • 2020-08-20
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    相关资源
    最近更新 更多