Francis Zabala
Francis Zabala

Reputation: 1067

Having trouble using async/await on mongoose 5

I have been trying to refactor the code here from mongoose on how to use it with lambda but have been failing miserably. I think it has to do on how improperly I use async/await. Based from the logs, the conn object is not being initialized as intended. Anyway, here are my codes.

db.js

const mongoose = require('mongoose');
const uri = 'mymongoURL';

module.exports.initDb = async function()  {
    return mongoose.createConnection(uri, {
    bufferCommands: false, // Disable mongoose buffering
    bufferMaxEntries: 0 // and MongoDB driver buffering
   });
}

index.js

const mongoose = require('mongoose');
let conn = null;
const db = require('./db');

exports.handler = async (event,context,callback) => {
context.callbackWaitsForEmptyEventLoop = false;

if (conn == null) {
  conn = await db.initDb();
  console.log("conn is still null: "+ conn == null);
  conn.model('Foo', new mongoose.Schema({
    promo: {
      type: String,
    }
  }, { collection: 'foo', timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' } } ));

  conn.model('Test', new mongoose.Schema({ name: String }));
}

    const FM = conn.model('Foo');
    let fooObj = new FM({promo:"Zimmer!"});
    fooObj.save(function(err, response) {
      console.log(err);
    });

    const M = conn.model('Test');
    let zim = new M({name:"Zim!"});
    zim.save(function (err, result){
    });
};

I apologize in advance on how I use async/await improperly.

Upvotes: 1

Views: 1649

Answers (1)

Johann
Johann

Reputation: 36

For db.js, you forgot to add await on createConnection function. Await should be use in async function.

const mongoose = require('mongoose');
const uri = 'mymongoURL';

module.exports.initDb = async function()  {
    return await(mongoose.createConnection(uri, {
    bufferCommands: false, // Disable mongoose buffering
    bufferMaxEntries: 0 // and MongoDB driver buffering
   }));
}

Upvotes: 2

Related Questions