我一直试图从猫鼬中重构代码,说明如何与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){
});
};对于我如何使用异步/等待不当,我事先表示歉意。
发布于 2018-06-29 07:52:46
对于db.js,您忘记添加对createConnection函数的等待。等待应该在异步功能中使用。
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
}));
}https://stackoverflow.com/questions/51041685
复制相似问题