Reputation: 1
Here is the function that I use for create users, if the user exist, which means the findOne has result, then all the rest is fine, but when the user is not exist, which means the findOne can not get any result, then it get into no response, even the console.log is not printed.
function createUser(payload) {
return Users.findOne({'username': payload.username})
.then(result =>{
console.log(result);
if(result){
res.render({message: 'Success registered.',
statusCode: '200',
result: result});
}else{
return {
message: 'Success registered.',
statusCode: '200'
};
}
})
.catch(err => {
console.log(err);
});
}
This is the user schema :
let mongoose = require('mongoose');
let timeZone = require('mongoose-timezone');
let userSchema = mongoose.Schema({
username:{
type: String,
required: true
},
password:{
type: String,
required: true
},
phone:{
type: Number,
required: true
},
email:{
type: String
},
role:{
type:String,
required: true
},
createdAt: {
type: Date,
default: Date.now
},
status:{
type:String
}
});
userSchema.plugin(timeZone);
let profile = module.exports = mongoose.model('profiles', userSchema);
Upvotes: 0
Views: 624
Reputation: 779
Your code never makes it to the catch
block if the user doesn't exist. If there is no result (e.g., the user doesn't exist), it goes through the else
block and returns a 200 code with a message (apparently incorrectly) stating that the user has been created.
See here in docs: findOne
returns null
if query has no results.
Upvotes: 1