我一直在尝试重构mongoose中的代码,以了解如何将其与lambda一起使用,但是却失败了。我认为这与我使用异步/等待的方式不正确有关。根据日志,conn对象未按预期初始化。无论如何,这是我的代码。
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){
});
};
我事先对我不正确地使用async / await表示歉意。
答案 0 :(得分:2)
对于db.js,您忘记在createConnection函数上添加等待。应该在异步功能中使用Await。
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
}));
}