QuikProBroNa QuikProBroNa - 7 months ago 52
Javascript Question

Node.js/mongoose: undefined is not a function

I have this MEAN app in which the users can upload their photograph. Here is the route for that:

var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/user');
var Verify = require('./verify');
var multiPart = require('connect-multiparty');
var multiPartMiddleWare = new multiPart();
var fs = require('fs-extra');
var path = require('path');

router.post('/edit', multiPartMiddleWare ,function(req, res) {
var file = req.files.file;
theuser = req.body.username;
console.log("User " + theuser + "..." + file);

var uploadDate = new Date();
console.log(file.path + '\n')
var tempPath = file.path;
var finalPath = path.join(__dirname, "../userphotos/", theuser + file.name);
console.log(finalPath);
var savePath = "/userphotos/" + theuser + uploadDate + file.name;

fs.rename(tempPath, finalPath, function (err){
if (err){
console.log(err)
} else {
User.find({"username":theuser}, function(err, userData){
var userd = userData;
userd.image = savePath;
console.log('\n' + userd + '\n'); // the userd is proper
userd.save(function(err){ //Error occurs HERE
if (err){
console.log("Error whilst saving file: " + err)
res.json({status: 500})
} else {
console.log("Image saved");

res.json({status: 200})
}
})
})
}
})
});


The image gets saved to my temp folder as well as the destination. However, when I try to save the source in to the user document, I get a
undefined is not a function
.

Here is my mongoose route:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');

var User = new Schema({
username: {
type: String,
unique: true
},
password: String,
image: {
type: String
},
bio: {
type: String
}
});

User.plugin(passportLocalMongoose);

module.exports = mongoose.model('User', User);


How do I resolve this issue?

Answer

I think you're using wrong function here:

User.find({"username":theuser}, function(err, userData){ ...

Try

User.findOne({"username":theuser}, function(err, userData){ ...
Comments