Reputation: 661
const Data = require('./Models/Data');
...
let example = new Data( sample );
example.save( function ( err ){
console.log('test);
if ( err ) {
console.log('Error saving Data. 'Error: ', err);
}
});
Any ideas why save() callback function never runs? I mean, the "test" text doesn't show up, while "example" is created just like it should (I mean, when I print it, it looks ok). Any ideas? TIA
Upvotes: 1
Views: 1106
Reputation: 18969
This typically occurs when you haven't connected to the database. You can create the model object but none of the Mongoose functions that operate on the database works. They fail silently instead. Make sure you connect with the connect function. You can also listen to the connection and error events to see that you actually get connected:
const dburl = `mongodb://localhost/testdb`;
mongoose.connect(dburl, { useMongoClient: true });
mongoose.connection.on('connected', () => { console.log(`Mongoose connected to ${dburl}`); });
mongoose.connection.on('error', (err) => { console.log(`Mongoose connection error: ${err}`); });
mongoose.connection.on('disconnected', () => { console.log('Mongoose disconnected'); });
Pay attention to the terminal when you start the app and look for Mongoose connected. Finally, you can turn on debug mode in Mongoose to see what's actually going on behind the scenes:
mongoose.set('debug', true);
You can add it right below the connect call, for example.
You don't have to use the promise method by the way. You can use the callback version that you're already using. Just make sure to correct the error with the missing ' in the console.log.
Upvotes: 0
Reputation: 612
As Nir Levy has already said: the then call can be an alternate way of saving the document. You can also try supplying the second argument in the save's callback as:
example.save((err, doc) => {
console.log('test');
if (err) {
console.log('Error while saving data: ', err);
} else {
console.log('document is: ', doc);
}
});
Also note that you missed a closing quotemark on the console.log() inside example.save callback
Can you also make sure that your mongodb server is running and you are connected to the mongodb server? if that maybe causing the problem?
Upvotes: 0
Reputation: 12953
Mongoose async save() function works with a function, which means you don't need to pass it a callback function, but rather use then/catch pattern:
const Data = require('./Models/Data');
...
let example = new Data( sample );
example.save()
.then(() => {
console.log('test);
})
.catch((err) => {
console.log('Error saving Data. 'Error: ', err);
});
see more here
Upvotes: 1