Error "DocumentNotFoundError: No document found for query "{ _id:xxx} - node.js

I cloned the object "preventivo",
when I run this code I have the following error:
(node:24548) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): DocumentNotFoundError: No document found for query "{ _id: 5ff6110e27bbf25fe45ce2b5 }" on model "preventivi"
i can't understand the error, can you help me?
i use node + mongoose + handlebars
thanks
//ROUTE CLONA PREVENTIVO
app.post('/preventivi/dbpreventivi/:id/clone' ,accessoSicuro,(req , res) =>{
Preventivi.findOne({
_id: req.params.id
})
.then(preventivo => {
var newdoc = new Preventivi(preventivo);
newdoc._id = mongoose.Types.ObjectId();
delete newdoc.__v;
newdoc.save();
console.log(newdoc._id)
req.flash("msg_successo", "Preventivo clonato correttamente");
res.redirect("/preventivi/dbpreventivi");
});
});
//fine route clona preventivo
Html:
<form action="/preventivi/dbpreventivi/{{_id}}/clone?_method=POST" method="post">
<input type="hidden" name="_method" value="POST">
<input onclick="return confirm('Vuoi clonare il preventivo: {{cliente}} {{codice}} ?');" type="submit" class="btn btn-warning btn-sm" value="Clona">
</form>

You can try add newdoc.isNew = true :
//ROUTE CLONA PREVENTIVO
app.post('/preventivi/dbpreventivi/:id/clone' ,accessoSicuro,(req , res) =>{
Preventivi.findOne({
_id: req.params.id
})
.then(preventivo => {
var newdoc = new Preventivi(preventivo);
newdoc._id = mongoose.Types.ObjectId();
newdoc.isNew = true;
newdoc.save();
console.log(newdoc._id)
req.flash("msg_successo", "Preventivo clonato correttamente");
res.redirect("/preventivi/dbpreventivi");
});
});
//fine route clona preventivo

Mine, was using "async map" incorrect way.
I did update some records in a "async map" method like below:
makerOrders.map(async makerOrder => {
....
try {
await Order.findByIdAndUpdate(makerOrder._id, {
remainder: makerOrder.remainder,
});
} catch (error) {
console.log(' order.save(); ' + err);
return err(`Maker order is not updated. ${err}`, 500);
}
...
});
Even using try catch didn't catch the error and it has got 3 days to solve!
Hope help somebody :)

Related

Not sure why my frontend and backend aren't connecting; is it an API issue? Help pls

The issue is that the connection doesn't seem to be going through. The error log doesn't show anything: there's no sign data is being sent to the database. E.g. when I log in, or sign up, I can see that I'm doing that in the console. No dice here.
Vue component:
<script>
import KitchenAssignment from "../models/kitchenAssignment";
export default {
name: 'sendAssignment',
data(){
return {
kitchenAssignment: new KitchenAssignment('', '', '', '')
};
},
methods: {
submitForm(){
this.$store.dispatch('auth/saveAssignment')
}
}
}
</script>
Pertinent bit of my auth.service.js file:
import axios from 'axios';
const API_URL = 'https://appname.herokuapp.com/api/auth/';
...
saveAssignment(kitchenAssignment){
return axios.post(API_URL + 'kitchenAssignments', {
kAName: kitchenAssignment.kAName,
startTime: kitchenAssignment.startTime,
endTime: kitchenAssignment.endTime,
minRoleRequired: kitchenAssignment.password
})
}
My routes file:
const { authJwt } = require("../middleware"); // nothing in here yet, just trying to be sure i can actually send data to database
const controller = require("../controllers/kitchenAssignment.controller.js");
module.exports = function(app) {
app.use(function(req, res, next) {
res.header(
"Access-Control-Allow-Headers",
"Origin, Content-Type, Accept"
);
next();
});
app.post('/api/auth/kitchenAssignments', controller.saveAssignment);
};
My controller file:
const db = require("../models");
const KitchenAssignment = db.kitchenAssignment;
const Op = db.Sequelize.Op;
//const { default: kitchenAssignment } = require("../../vue-vuex-jwt-auth-master/src/models/kitchenAssignment");
exports.saveAssignment = async (req, res) => {
try {
const kitchenAssignment = await KitchenAssignment.create({
kAName: req.body.kAName,
startTime: req.body.startTime,
endTime: req.body.endTime,
minRoleRequired: req.body.minRoleRequired
});
}
catch (error) {
res.status(500).send({ message: error.message });
}
}
Not sure it's relevant, but here's my input area for the user in the .vue component? Maybe it's incorrect somehow.
<template>
<div class="container">
<header class="jumbotron">
<h3>{{content}}</h3>
<div>
<input v-model="kitchenAssignment.kAName"
placeholder="Input kitchen assignment name."
/>
<input v-model="kitchenAssignment.startTime"
placeholder="Input start time."
type="time"/>
<input v-model="kitchenAssignment.endTime"
placeholder="Input end time."
type="time"/>
<input
v-model="kitchenAssignment.minRoleRequired"
placeholder="Select minium role required."
v-validate="'required|pattern:^(Kitchen Leader|Sous Chef|Line Cook|Junior Cook|Dishwasher)$'"
name="minimum role required"
/>
<button #click="submitForm">Enter</button>
</div>
</header>
</div>
</template>
Would appreciate any help. I've tried a lot of stuff, can't recall everything but it led me to this point. Been reading up on Apis to no avail.

How i can update the image url if user select new file other wise image url not update in nodejs

I'm creating a book project where i'm saving the books images into the cloudinary and there url's saving into the mongodb database which are working well.But i'm facing issue during the updation of a book when i update my book then the url of book is not updated and console giving me error Cannot read properties of undefined (reading 'map') where i want to update the url with new one url of image but its not working Please any one can solve this
this is my update.js code
module.exports.updateBook = async (req, res) => {
try {
const { id } = req.params;
const book = req.body;
const singleBook = await Book.findById(id);
// Delete Prvious Url From the Cloudinary and Reset It to the new ..
cloudinary.v2.uploader.destroy(singleBook.image[0].filename);
book.image = req.files.map((f) => ({
url: f.path,
filename: f.filename,
}));
console.log("Single Book ===", singleBook);
const updateBook = await Book.findByIdAndUpdate(
id,
{ $set: book },
{ new: true }
);
if (updateBook) {
res
.status(200)
.json({ success: true, message: "Book Updated Successfully!" });
} else {
res.status(400).json({
success: false,
message: "Book Not Updated There Is an error!",
});
}
} catch (err) {
console.log("** Error In Update Book **", err.message);
}
};
this is my route handler
const express = require("express");
const router = express.Router();
const book = require("../controller/book");
const authenticated = require("../middleware/verifyToken");
const multer = require("multer");
const { storage } = require("../cloudinary");
const upload = multer({ storage });
// Update Book By ID
router.route("/:id").put(authenticated, upload.array("image"), book.updateBook);
module.exports = router;
this is my reactjs update method
const formik = useFormik({
initialValues: {
title: book?.title,
author: book?.author,
price: book?.price,
description: book?.description,
image: book?.image[0].url,
},
validationSchema: validationSchema,
enableReinitialize: true,
onSubmit: (values) => {
const formData = new FormData();
formData.append("title", values.title);
formData.append("price", values.price);
formData.append("description", values.description);
formData.append("author", values.author);
formData.append("image", values.image);
Axios.put(`${Base_URL}/book/${id}`, values, {
headers: {
Authorization: authHeader(),
},
})
.then((res) => {
if (res.data.success) {
message = res.data.message;
setAlertContentupdate(message);
setAlertupdate(true);
setTimeout(() => {
handleClose();
navigate(`/book/${id}`);
getBook();
console.log("Response == ", res.data.message);
}, 3000);
}
})
.catch((err) => {
console.log("Error ====", err.message);
});
},
this is my jsx code for updating book
<form onSubmit={formik.handleSubmit}>
<TextField
name="title"
autoFocus
margin="dense"
label="Book Title"
type="text"
fullWidth
variant="standard"
value={formik.values.title}
onChange={formik.handleChange}
error={formik.touched.title && Boolean(formik.errors.title)}
helperText={formik.touched.title && formik.errors.title}
/>
<TextField
name="author"
margin="dense"
label="Book Author"
type="text"
fullWidth
variant="standard"
value={formik.values.author}
onChange={formik.handleChange}
error={formik.touched.author && Boolean(formik.errors.title)}
helperText={formik.touched.author && formik.errors.author}
/>
{/* File Input Field */}
{/* Picture Input */}
<input
type="file"
name="image"
accept=".png, .jpeg, .jpg"
onChange={(e) => {
formik.setFieldValue("image", e.target.files[0]);
}}
/>
{formik.touched.image && formik.errors.image ? (
<div style={{ color: "#e53935", fontSize: "12px" }}>
{formik.errors.image}
</div>
) : null}
{/* Price Input Field */}
<TextField
name="price"
margin="dense"
label="Book Price"
type="text"
fullWidth
variant="standard"
value={formik.values.price}
onChange={formik.handleChange}
error={formik.touched.price && Boolean(formik.errors.price)}
helperText={formik.touched.price && formik.errors.price}
/>
<TextField
name="description"
margin="dense"
label="Book Description"
type="text"
fullWidth
variant="standard"
value={formik.values.description}
onChange={formik.handleChange}
error={
formik.touched.description &&
Boolean(formik.errors.description)
}
helperText={
formik.touched.description && formik.errors.description
}
/>
<DialogActions>
<Button onClick={handleClose}>Cancel</Button>
<Button type="submit">Update</Button>
</DialogActions>
</form>
In formik i'm getting the book data from back end api's and putting into the formik initial values But Problem is that when i clicked on the update button then the backend compiler giving me this error Cannot read properties of undefined (reading 'map') Please any one can solve this thanks in advance
So this line looks like the issue for me:
cloudinary.v2.uploader.destroy(singleBook.image[0].filename);
Using this is actually deleting your asset so you are probably want to just update it using the explicit API. See https://cloudinary.com/documentation/image_upload_api_reference#explicit
So maybe something like:
cloudinary.v2.uploader.explicit(singleBook.image[0].filename);
Let me know if this helps?

Multer - Cannot Read Property "path" of Undefined

I'm trying to upload a single image to mongo using multer but I keep getting this error while trying to access the image path like:
TypeError: Cannot read property 'path' of undefined
at router.post (D:\Workspace\AdminBootstrap\routes\admin_index.js:74:29)
Here's my code to upload the image:
router.post('/add-category', uploads.single('category_image'), (req, res) => {
let title = req.body.title;
console.log('Category Title:\t' + title);
let slug = title.replace(/\s+/g, '-').toLowerCase();
let catImage = req.file.path; // error occurs here
console.log(catImage);
let category = new Category({
title: title,
slug: slug,
image: catImage
});
category.save()
.then(result => {
if (result) {
console.log('Saved Category:\t' + result);
res.redirect('/admin/home');
}
})
.catch(errors => {
console.error('Error Saving Category:\t' + errors);
});
});
Here's my template:
<label>Upload Image</label>
<input name="category_image" class="form-control" type="file" accept="image/*" id="selImg" onchange="showImage.call(this)">
<img src="#" id="imgPreview" style="display: none; height: 100px; width: 100px">
Can anyone explain to me why the path is throwing an error?
The path is throwing an error because "file" is not defined inside "req" object.
It is probably defined in "req.body" object. Use
console.log(req.body)
to confirm.
Since title is defined on "req.body", "file.path" also should be defined on the same object.
While setting up your HTML, your form should have an attribute of
enctype="multipart/form-data"
This will save your file in the path variable

post input type file to server node.js from angular service call

I have simple multipart formdata
<form action="/upload" enctype="multipart/form-data" method="post">
<span class="btn btn-file">
<input type="file" name="file" ng-model="file"/>
<span class="btn btn-primary" ng-click="upload()">Upload</span>
</span>
</form>
What I want to do it, post all the information related to file to the server written in node.js
server.js This is file upload handler written in node. Formidable expects all parameters of a file.
upload: function uploadfn (req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
// `file` is the name of the <input> field of type `file`
var old_path = files.file.path,
file_size = files.file.size,
file_ext = files.file.name.split('.').pop(),
index = old_path.lastIndexOf('/') + 1,
file_name = old_path.substr(index),
new_path = path.join(process.env.PWD, '/uploads/', file_name + '.' + file_ext);
fs.readFile(old_path, function(err, data) {
fs.writeFile(new_path, data, function(err) {
fs.unlink(old_path, function(err) {
if (err) {
res.status(500);
res.json({'success': false});
} else {
res.status(200);
res.json({'success': true});
}
});
});
});
});
}
The things I'm stuck at is, I have service call ready in angular as follows:
service.factory('FileUpload', function ($resource) {
return $resource('/upload', {}, {
post: {method: 'POST'}
});
});
This call hits the backend from angular controller as follows
$scope.upload = function(){
console.log($scope.file);
FileUpload.post(function(){
});
}
I'm not sure how to post the file submit so that node can catch it. Also $scope.file is undefined.
Please help me solve this.
There's a good directive for file upload for angularjs, try to use it
https://github.com/danialfarid/angular-file-upload

AngularJS updating mongoDB

I'm having some trouble updating my mongoDB from a Node server. Sorry, but I'm having some trouble tagging the code. Might come out as regular text.
The error i get is on the node server and states as follows:
Cast to string failed for value "undefined" at path "text"
Here's my code:
web-server:
app.post('/updateArticle/', function(req, res){
console.log("Updating article");
articleModel.update(
{id: req.id},
{$set: {title: req.title, text: req.text}});
"services:
wikiServices.factory('articleService', function($http, $routeParams){
return{
getArticles: function(callback){
$http.get('articles/' + $routeParams.article).success(callback);
},
updateArticle: function(article, callback){
$http.post('updateArticle/', article);
}
};
controllers:
wikiControllers.controller('articleController', ['$scope', 'articleService', '$routeParams', '$sanitize',
function($scope, articleService, $routeParams, $sanitize){
articleService.getArticles(function(result){
$scope.article = result[0];
console.log($sanitize(result[0].text));
$scope.articleHTML = $sanitize(result[0].text);
});
$scope.update = function(article, callback){
articleService.updateArticle(article);
console.log("test");
};
articleEdit:
<div text-angular="text-angular" ng-model="article.text"></div>
<div ng-bind-html="article.text"></div>
Tilbake
<button ng-click="update()">Lagre forandringer</button>
I forgot to send the object in the HTML-function. update("article.text");

Resources