user1008531 user1008531 - 3 months ago 20
Node.js Question

mongoose check if getById has a field

I wish to search a document by Id and check if that document has a certain field. If user has the field, the image with that filename will be deleted. But there is a problem with my query

exports.updateImage = function(userId, image, cb){
console.log(image);
userSchema.findById(userId, { image : {$exists : true}}, function(err, user){
console.log(user);
console.log(err);
if(user){
fs.unlick('./public/' + user.image);
}
});
userSchema.findByIdAndUpdate(userId, {
"image" : image
}, cb);
};

Answer

Never mind, I lost an ')' in the end, I read the error, but after looking and looking, I couldn't find the typo, but now I see it. My mistake

userSchema.findById(userId, { image : {$exists : true}}, function(err, user){       if(user){
        fs.unlick('./public/' + user.image);
    }
});
userSchema.findByIdAndUpdate(userId, {
    "image" : image
}, cb);