Reputation: 816
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?
Upvotes: 0
Views: 81
Reputation: 2777
Change this var userd = userData;
to var userd = userData[0];
. userData got array of several document (may include only one doc in array) so need to get one document to do modifications.
Upvotes: 0
Reputation: 2755
You are using User.find()
which returns an array, and hence you cannot save
it. You can use userData[0]
to get the first User
from the array or just use User.findOne()
which will also return the first User
matched.
Upvotes: 1
Reputation: 11929
I think you're using wrong function here:
User.find({"username":theuser}, function(err, userData){ ...
Try
User.findOne({"username":theuser}, function(err, userData){ ...
Upvotes: 1