Friday, 9 June 2017

Can't update (.put) entries in mongoose database with ng-file-upload

I'm getting to now the MEAN-Stack right now and therefore I'm not that experienced.

I have a image database with tagging functionality and I also want to update tags, if needed. I'm using ng-file-upload, express, multer and mongoose to upload and to store my images with the tags. If you want to have a detailed look you can download it from my repo.

This is my mongoose model/schema

var mongoose = require('mongoose');

var TagSchema = mongoose.Schema({
    ImageObjects: String,
    CreatorArtist: String,
    Question1: String,
    Question2: String,
    info: Array,
});

var UploadSchema = mongoose.Schema({
    name: String,
    tags: TagSchema,
    created: Date,
    file: Object
});



module.exports = mongoose.model('Upload', UploadSchema);

For 'PUT'–ting i got a app controller like this:

var app = angular.module('fileUpload', [
    'ngFileUpload',
    'ngResource',
    'ngRoute'
]);

app.config(function ($routeProvider, $locationProvider) {
    $locationProvider.hashPrefix('');

    $routeProvider.
    when('/', {
        templateUrl: '../views/home.html'
    }).
    when('/uploadForm', {
        templateUrl: '../views/uploadForm.html'
    }).
    when('/updateForm', {
        templateUrl: '../views/updateForm.html'
    }).
    otherwise('/');

});

app.controller('formCtrlUpdate', ['$http', 'Upload', '$scope', '$routeParams', function ($http, Upload, $scope, $routeParams) {

    // console.log($routeParams);

    $http.get('/uploads/update/' + $routeParams.uuid + '/' + $routeParams.filename).then(function (response) {
        console.log(response.data);
        $scope.image = response.data;
        console.log("Beginning");
    });

    $scope.submit = function () {

        Upload.upload({
            // url: '/uploads',
            url: '/uploads/update/' + $routeParams.uuid + '/' + $routeParams.filename,
            method: 'post',
            data: {_method:'put', file: $scope.upload}
            // data: $scope.upload
        }).then(function (response) {
            console.log(response.data);
            $scope.all.push(response.data);
            $scope.upload = {};
            console.log("Update")
        })
    }
}]);

This is my routing, so I can display and update images as they are requested (simplified, the repo has the complete list of routes). Please note the .put part, I think this is the important part here

var express = require('express');
var router = express.Router();
var fs = require('fs');
var Upload = require('../models/upload');
var multer = require('multer');
var upload = multer({
    dest: 'uploads/'
});
var author;
var _ = require('underscore');


/**
 * Create's the file in the database
 */
router.post('/', upload.single('file'), function (req, res, next) {
    var newUpload = {
        name: req.body.name,
        tags: req.body.tags,
        created: Date.now(),
        file: req.file

    };
    Upload.create(newUpload, function (err, next) {
        if (err) {
            next(err);
        } else {
            res.send(newUpload);
        }
    });

});



router.put('/update/:uuid/:filename', function (req, res) {
    Upload.findOneAndUpdate({
            'file.filename': req.params.uuid,
            'file.originalname': req.params.filename
        }, {
            $push: {
                tags: req.body.tags
            }
        },
        function (err, upload) {
            if (err) next(err);
            else {
                res.send(upload);
            }
        });
});


// /**
//  * Gets the list of all files from the database
//  */
router.get('/', function (req, res, next) {
    Upload.find({}, function (err, uploads) {
        if (err) next(err);
        else {
            res.send(uploads);
        }
    });
});


/**
 * Gets a file from the hard drive based on the unique ID and the filename
 */

router.get('/:uuid/:filename', function (req, res, next) {
    Upload.findOne({
        'file.filename': req.params.uuid,
        'file.originalname': req.params.filename
    }, function (err, upload) {
        if (err) next(err);
        else {

            // res.send(upload);
            res.set({
                "Content-Disposition": 'attachment; filename="' + upload.file.originalname + '"',
                "Content-Type": upload.file.mimetype
            });
            fs.createReadStream(upload.file.path).pipe(res);
        }
    });
});


router.get('/image/:uuid/:filename', function (req, res, next) {
    Upload.find({
        'file.filename': req.params.uuid,
        'file.originalname': req.params.filename
    }, function (err, upload) {
        if (err) next(err);
        else {
            res.send(upload);
        }
    });
});

router.get('/update/:uuid/:filename', function (req, res, next) {
    Upload.find({
        'file.filename': req.params.uuid,
        'file.originalname': req.params.filename
    }, function (err, upload) {
        if (err) next(err);
        else {
            res.send(upload);
        }
    });
});

module.exports = router;

this is my index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>File Upload Example</title>
    <link rel="stylesheet" href="/css/normalize.css">
    <link rel="stylesheet" href="css/main.css">
    <link rel="stylesheet" href="css/jquery.steps.css">

    <script type="text/javascript" src="/vendor/angular.min.js"></script>
    <script type="text/javascript" src="/vendor/ng-file-upload-all.min.js"></script>
    <script type="text/javascript" src="/vendor/angular-resource.js"></script>
    <script type="text/javascript" src="/vendor/angular-route.min.js"></script>
    <script type="text/javascript" src="/javascripts/fileUpload.js"></script>

</head>


<body ng-app="fileUpload">

    <div ng-view></div>


</body>

</html>

and this ist my update form where i should be able to update my tags

<div ng-controller="formCtrlUpdate" id="example-form" action="#">
    <h2>Update</h2>
    <ul>
        <li ng-repeat="upload in image">
            <a ng-href=''></a></br>
            <img ng-src='' />


            <form ng-submit="submit()">
                <legend>Update file here:</legend>
                <label for="name">Name:</label>
                <input type="text" name="name" id="name" ng-model="upload.name" />
                <br/>

                <label for="CreatorArtist">Artist:</label>
                <input type="text" name="CreatorArtist" id="CreatorArtist" class="demo-default" ng-model="upload.tags.CreatorArtist" />
                <br/>

                <label for="info">Image Description:</label>
                <input type="text" name="info" id="info" ng-model="upload.tags.info" />
                <br/>

                <input type="submit" value="Update" />

            </form>
        </li>

    </ul>
</div>

Possibly unhandled rejection: I get a error like this in the browserenter image description here

TypeError: Cannot read property '$each' of undefined And something like this in my console enter image description here

I tried to look up, if there is a problem with 'PUT'-ting files with ng-file-upload but I can't implement the suggested solutions in the github issues. Can you point me in the right direction, so I can update existing tags?



via basedian

No comments:

Post a Comment