【问题标题】:Mongoose and MongoErrorMongoose 和 MongoError
【发布时间】:2020-05-05 07:36:10
【问题描述】:

我遇到了一个奇怪的错误。我猜这是因为我没有正确处理错误以获取更多信息。这是我得到的错误。我在这里搜索过,但没有成功找到类似的东西。文档让我很困惑。

{"name":"MongoError","level":"error","service":"user-service"}

这是我的连接脚本:

const mongoose = require('mongoose'),
      logger   = require('./logging');

async function connect(){

  await mongoose.connect("mongodb://localhost:27017/fdData")
    .catch(error => {
      logger.error(error);
  });
}

async function disconnect(){
    await mongoose.disconnect()
    logger.info('DB disconnected');
}

module.exports= {connect, disconnect}
}

module.exports= {connect, disconnect}

这就是我所说的。 (这只是脚本的一个小sn-p)。

更新于 20 年 1 月 20 日@太平洋标准时间上午 1024 点。

  • (从 weather.js 中删除了 db.connect() 和 db.disconnect。db.connect 发生在 app.js 上。 weather.js 检查猫鼬就绪状态并报告 状态 1(已连接)。
  • 添加了 mongoose Op 结果到记录器,所以现在我们可以看到 在控制台中尝试了猫鼬操作。
//schema setup

const weatherSchema = new mongoose.Schema({
        condition: String,
        temp: Number,
        windDir: String,
        windSpd: Number,
        windGust: Number,
        windChill: String,
        humidity: Number,
        icon: String,
        tempIcon: String,
        date: String,
        updated: String,
    });

const weatherWarningSchema = new mongoose.Schema({
        warning: String,
        warningStart: String,
        warningExpire: String,
        warningBody: String,
        id: String,
        date: String,
    });

const Weather = mongoose.model("weather", weatherSchema);
const Warning = mongoose.model("warning", weatherWarningSchema);

currentWeather=[];

async function saveWeather(update){

/////////commented Out for troubleshooting//////////
    // await db.connect() 
    //     .then(error=>{logger.error(error)
/////////end comments/////////////
            Weather.findOneAndUpdate({date: update.date}, 
                {   date:update.date, 
                    condition:update.condition,
                    temp:update.temp, 
                    windChill:update.windChill, 
                    windDir:update.windDir, 
                    windSpd:update.windSpd, 
                    windGust:update.windGust, 
                    humidity:update.humidity, 
                    icon:update.icon, 
                    tempIcon:update.tempIcon, 
                    updated:update.updated}, 
                {upsert:true,
                new: true,}, 
                function(error, result){
                    if (error){
                        logger.error(error);
                    } else{
                        console.log(result);
                        logger.info('Weather Saved to DB '+moment().utcOffset(-8).format('HH:mm'))
                    }
                })
                console.log('Mongoose Ready State: '+mongoose.connection.readyState)
///////commented out for troubleshooting////////
        // }).then((res, error)=>{
        //     if(error){
        //         logger.error(error)
        //     }
            // db.disconnect();
        // })
/////////end comments/////////

}

这是控制台中完整的初始输出:

正在获取刻录数据...

正在更新天气数据...

(node:3890) DeprecationWarning:当前的服务器发现和监控引擎已被弃用,并将在未来的版本中删除。要使用新的服务器发现和监控引擎,请将选项 { useUnifiedTopology: true } 传递给 MongoClient 构造函数。

(node:3890) DeprecationWarning:当前的 URL 字符串解析器已被弃用,并将在未来的版本中删除。要使用新的解析器,请将选项 { useNewUrlParser: true } 传递给 MongoClient.connect。

{"message":"Dashboard Server 运行在 3000","level":"info","service":"user-service"}

{"message":"Crewsense 令牌是当前的","level":"info","service":"user-service"}

{"message":"A911 令牌是当前的","level":"info","service":"user-service"}

Mongoose 就绪状态:1

{ _id: 5e25ef3d8c936f22f7722326, 日期:'2020-01-20', __v: 0, 条件:'晴天', 湿度:96, 图标:'sunny.png', 温度:34, tempIcon: 'https://cdn.aerisapi.com/wxicons/v2/cold.png', 更新:'01/20/20 10:19', 风寒:'34', windDir: 'N', 阵风:0, 风速:0 }

{"message":"Weather Saved to DB 10:19","level":"info","service":"user-service"}

正在保存刻录数据...

刻录数据已保存。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    错误告诉你db disconnected,发生的事情是你没有等待updateOne函数返回的承诺。

    您应该在此处添加await 来解决此问题。

    await db.connect()
        .then(async (error) {
           logger.error(error)
           console.log('Saving Weather... '+mongoose.connection.readyState) //"Saving Weather...1"
    
           await Weather.updateOne({date: update.date}, 
                       ... )
    
        }).then((res, error)=>{
           if(error){
              logger.error(error)
           }
           db.disconnect();
       })
    

    【讨论】:

    • Tom 我不能在 Weather.updateOne 前面放置 await。它告诉我它不是异步函数。
    • 另外,带有 Weather.updateOne() 的 .then() 不应该在下一个 .then() 之前完成吗?
    • 不,它的承诺被忽略,所以代码不会等待它。
    • 我更新了上面的代码,因为我一直试图弄清楚它没有成功。我已经向控制台添加了额外的输出,并且我也更新了该输出。代码的初始运行工作正常。但是当我的应用程序调用该函数以定时间隔再次运行时,输出是这样的:(下一条评论)
    • 正在更新天气数据... Mongoose 就绪状态:1 { _id:5e25ef3d8c936f22f7722326,日期:'2020-01-20',__v:0,条件:'晴天',湿度:96,图标: 'sunny.png',温度:34,tempIcon:'cdn.aerisapi.com/wxicons/v2/cold.png',更新:'01/20/20 10:19',windChill:'34',windDir:'N',windGust:0,windSpd:0 } {"message":"天气保存到 DB 10:31","level":"info","service":"user-service"}
    【解决方案2】:

    我明白了!!!

    Mongoose 和 MongoDB 运行正常。问题在于currentWeather 数组的分配。我将新数据推送到数组而不是替换它。因此,我的脚本不断将currentWeather[0] 放入我的数据库中,这就是为什么它会运行一次而不是再次运行的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-27
      • 1970-01-01
      • 2015-07-18
      • 2020-10-03
      • 2015-01-25
      • 1970-01-01
      • 2014-01-15
      • 1970-01-01
      相关资源
      最近更新 更多