猫鼬TypeError:无法读取null的属性“ insertOne”

时间:2020-02-19 16:54:40

标签: mongodb mongoose mongoose-schema

我一直在努力弄清我整个上午都在搞砸。

首先是问题: 当我调用myModel.create()时,我在控制台中得到了这一点:

TypeError: Cannot read property 'insertOne' of null

模式和模型:

const callSchema = new mongoose.Schema({
        date: Date,
        times: {
            dispatch: String,
            clear: String
        },
        incident: Number,
        calltype: String,
        address: {
            streetAddress: String,
            city: String,
            state: String,
            zip: String
        },
        recall: [ 
            {type: mongoose.Schema.Types.ObjectId,
            ref: "User"}],
    });
const callData = mongoose.model("callData", callSchema);

现在提供数据和功能:

//dummy data:

var call = {
        date: '2020-02-19T08:35:04.803Z', 
        times: {
            dispatch: '1800', 
            clear: '1900'},
        incident: 2000599,
        calltype: 'medical', 
        address: { 
            streetAddress: '1200 Southgate', 
            city: 'Pendleton',
            state: 'OR',
            zip: '97801'},
        recall: ["5e4b5ac03e6a9e3ed521ab80"]
        };

function newCall(runData, times, personell){
    console.log(runData);

    callData.create(runData);
}

newCall(call);

我做了什么:

我注释掉了除模式和数据中的日期以外的所有内容,以尝试缩小问题的范围。这没有改变任何行为,它继续引发相同的错误。我环顾四周,其他人也遇到了类似的问题,但是我更正了他们建议的内容(将类型:更改为呼叫类型:),但找不到在架构中弄乱的内容。

任何帮助将不胜感激。

-亚当

1 个答案:

答案 0 :(得分:0)

问题出在我的数据库连接中。我没有安装它来正确等待。因此,这是一个异步问题,现在可以通过正确设置我的连接函数来解决,以等待完成后返回。

例如:

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



async function connect(){

//I had to place mongoose.connect(...)... in side of the const connected.
  const connected =  mongoose.connect("mongodb://localhost:27017/fdData", { 
    useNewUrlParser: true,
    useUnifiedTopology: true,
    bufferCommands: false,
    useFindAndModify: false,
});

  let con = mongoose.connection;
  con.on('error', logger.error.bind(logger, 'connection error:'));
  con.once('open', function() {
    logger.info('DB Connected');
  });

  mongoose.connection.on('disconnected', function(){
    console.log("Mongoose default connection is disconnected");
});

process.on('SIGINT', function(){
  mongoose.connection.close(function(){
      console.log("Mongoose default connection is disconnected due to application termination");
      process.exit(0)
  });
});

//I had to ADD this return as I did not have it.
return connected;

}

async function disconnect(){
    await mongoose.disconnect()
}

module.exports= {connect, disconnect}

通过执行这些操作,强制我的代码等待执行其余的操作,直到数据库正式连接为止。

-亚当