Reputation: 4173
I was using Mongoose 4.13.11
and my code was working as expected but as soon as I upgraded to 5.0.15
I started to have the following error TypeError: Cannot read property 'catch' of undefined
when I try to save my object and an error is found.
I've read around the issue seems to be that the Save()
function does not return a Promise
, I am using bluebird
and everything was working fine on the previous Mongoose
version 4.13.11
What am i missing or doing wrong because the .catch()
should work as implemented.
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: "[email protected]",
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);
});
Upvotes: 0
Views: 1045
Reputation: 4912
Two approaches to invoke save in mongoose
Promise
newUser.save().
then((data) =>{
console.log("saved data ",data);
res.json({ message: 'User created!' });
}).catch(function (error) {
console.log(error);
res.json({ message: 'User not created!' });
});
Callback
newUser.save(function(err,data) {
if (err){
console.log(error);
res.json({ message: 'User not created!' });
}
else{
console.log("saved data ",data);
res.json({ message: 'User created!' });
}
})
You could enable promise in mongoose by setting this
mongoose.Promise = global.Promise;
Documentation http://mongoosejs.com/docs/models.html
Upvotes: 1