Reputation: 426
I am new to node.js and mongoDB. I have been following book on the subject which works successfully. However, when I tried to practice the learning... it fails while saving the record.
Can you please guide me in my initial learning step please?
I confirm that node.js and mongoDB is installed and running....
my code page …
var mongo = require('mongoose');
const UserSchema = new mongo.Schema({
name: {
type: String,
trim: true,
required: 'Name is required'
},
email: {
type: String,
trim: true,
unique: 'Email already exists',
match: [/.+\@shetty\.org\.uk/, 'Please fill a valid email address for your domain only'],
required: 'Email is required'
},
hashed_password: {
type: String,
required: "Password is required"
},
status: {
type: String,
enum: ['New','Active','Disabled','Banned'],
default: "New"
},
salt: String,
updated: Date,
created: {
type: Date,
default: Date.now
}
});
var User = mongo.model('User', UserSchema);
var user1 = new User({
name: 'Avinash',
email: '[email protected]'
});
var user1 = new User({
name: 'Avinash',
email: '[email protected]'
});
mongo.promise = global.promise;
mongo.connect('mongodb://localhost/mongotest',{useNewUrlParser: true});
console.log(user1);
user1.save((err, result) => {
if (err) {
console.log('Error while saving');
}else{
console.log("Successfully saved record!");
}
});
mongo.disconnect();
the console.log outputs this ….
$ node index.js
{ status: 'New',
_id: 5bb8ca9a348028b4d4663544,
name: 'Avinash',
email: '[email protected]',
created: 2018-10-06T14:45:46.348Z }
Error while saving
(node:46292) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
Please do guide... :(
Upvotes: 0
Views: 116
Reputation: 483
The save()
method is asynchronous, which means that your code will continue to run the next instruction before the async one is finished.
Right after the save call you're executing mongo.disconnect()
which will kill your instance, before save()
is finished.
Solution:
Don't call mongo.disconnect()
until after the save()
operation is finished and your callback has been executed.
Additional errors:
I also notice that you've declared the hashed_password
property of the user schema as required, while not providing a password when creating an instance of user
. This will cause the validation to fail.
Upvotes: 1