【发布时间】:2018-04-19 18:41:22
【问题描述】:
我使用的是 Mongoose 4.13.11,我的代码按预期工作,但是当我升级到 5.0.15 时,当我尝试保存我的对象并发现错误时,我开始出现以下错误 TypeError: Cannot read property 'catch' of undefined。
我读过的问题似乎是Save() 函数没有返回Promise,我正在使用bluebird,并且在之前的Mongoose 版本4.13.11 上一切正常
我错过了什么或做错了什么,因为.catch() 应该按实施方式工作。
app.ts
mongoose.Promise = bluebird;
mongoose.connect(mongoUrl).then(
() => { /** ready to use. The `mongoose.connect()` promise resolves to undefined. */ },
).catch(err => {
console.log("MongoDB connection error. Please make sure MongoDB is running. " + err);
// process.exit();
});
Home.ts
let user: userInterface = {
email: "foo@bar.com",
firstName: "Brian",
lastName: "Love",
password: "as",
role: 1,
accountType: 1
};
var newUser = new User(user); // create a new instance of the User model
// save the newUser and check for errors
var a= newUser.save(function(err) {
if (err){
return err;
}
res.json({ message: 'User created!' });
}).catch(function (error) {
console.log(error);
});
【问题讨论】:
-
以前工作过吗?不知怎的,我对此表示怀疑。
newUser.save(function(err) {应该是newUser.save().then(() => */ something on success /* ).catch(甚至只是newUser.save().then(null, err => { ... }),因为毕竟catch()只是then()的第二个参数的糖。你不要像这样混合回调和承诺,如果以前没有抛出错误,那么它就是一个错误。 -
@NeilLunn 是的,运行良好。我试过你的代码,现在我得到
TypeError: Cannot read property 'then' of undefined它没有返回一个承诺 -
好吧,
.save()要么将callback作为参数(就像您尝试过的那样),要么像我展示的那样返回Promise。但永远不要两者都像您的列表显示。如果您收到Cannot read property 'then',我会怀疑这不是标准的猫鼬Document对象,并且您的代码中的其他内容实际上破坏了这一点。当然还有你的callback。 -
@NeilLunn 正在执行一个错误(正如我正在测试
catch()所预期的那样)errmsg: 'E11000 duplicate key error collection: admin.users index: email_1 dup key: { : "foo@bar.com" }',所以正在使用err回调......但是随后每个教程都会处理错误同样...我不知道为什么这个err不是一个承诺
标签: node.js mongodb typescript express mongoose