I have tried several methods to delete my photo, especially using fs.unlink but it seems not working at all, you can see from picture below that i save my photos in assets->img->products
and so my database looks like this
and my code looks like this
router.get("/admin/products/:id/delete", (req, res) => {
Product.findByIdAndRemove(req.params.id, (err, photo) => {
if (err) {
req.flash("error", "deleting photo failed");
return res.render("/admin/products/");
}
fs.unlink(photo.image1, function() {
console.log(photo.image1);
return res.redirect("/admin/products");
});
});
});
what is wrong from my code that did not delete my photo from my file?
It can not delete photos because you are passing the relative path as the first parameter.
photo.image1 = assets/img/products/image1.jpg
Try passing the passing the absolute path( from the root directory of your machine).
fs.unlink("absolute-path-to-assetsParentFolder" + photo.image1, function() {
console.log(photo.image1);
return res.redirect("/admin/products");
});
Related
I've been working on one of my first API projects with NodeJS, Express and MongoDB. I can save new documents into the database with collection.insertOne(newDocument) method but I can not take existing documents and output them using collection.find({}).
Can you please help me:')
export const visualizeUser = (req, res) => {
console.log("you are searching the user with username " + req.body.username);
users.find({username: 'yavuz'}, (err, data) => {
if(err)
console.log(err);
else
console.log(data);
});
}
thats the code I have written.
MongoInvalidArgumentError: Argument "options" must not be function
and that is the error I am getting.
Your help is really appreciated.
Like error message is saying, you cannot pass function as options argument.
Look here: docs
Your code should look like this:
const visualizeUser = async (req, res) => {
try{
console.log("you are searching the user with username " +
req.body.username);
let data = await users.find({username: 'yavuz'});
console.log(data)
} catch(e) {
console.log(e)
}
}
I am using imagemagick to covert file on node.
router.post('/route, upload.array('file'), async (req, res, next) => {
const files = req.files;
Promise.all(files.forEach(async (file) =>{
await fileconvert(file);
}));
...some db create
return res.send(createdId)
}
//from here different file
import im from 'imagemagick';
function fileconvert(file) {
return new Promise((resolve,reject)=>{
if(file.mimetype === "specialcase") {
im.convert(
[
file.path, '-format', 'png', 'newFile.png'
],
(err, stdout) => {
if(err) reject(err)
resolve(stdout);
}
)
}
//if not special-case without this, it doesn't work.
resolve();
})
}
In front-side, I'm using axios api call.
I am hoping that after fileconvert finished, then res.send(createdId).
Everything works fine, except that if too large file converted, I get broken image.
It may has file on exact directory but it hasn't converted fully yet.
It seems if file created, PASS. How can I get fully converted image...
Process on front-side is "Upload file => if createdId exists => route page
Thanks for your help.
I want zip a folder which contains few files. I am using zip-folder and 7zip-min modules they are working fine. But, I would like to add some parameters to it, like compression level and directory size and so on.
If it is not possible with this module, Can anyone provide other suggestions?
Here is my code :
Example 1-
const zipFolder = require('zip-folder');
zipFolder('./folder', './compressed.zip', function(err) {
if(err) {
console.log('something went wrong!', err);
} else {
console.log('done with compressing');
}
});
Example 2-
const _7z = require('7zip-min');
let pack = _7z.pack('./folder', './compressed.7z', err => {
console.log('I am done with compressing')
});
I'm following a simple tutorial.
Thing is, I'm using momngoose instead of Mongo.
I had no problems until I get to this point:
app.get('/', (req, res) => {
db.collection('quotes').find().toArray((err, result) => {
if (err) return console.log(err)
// renders index.ejs
res.render('index.ejs', {quotes: result})
})
})
With this, the quotes can be accessed and manipulates on index.ejs
now, I tried doing this:
app.get('/theroute', (req, res) => {
MyMongoModel.find()
.then(documents => {
res.render('index.ejs', *not entirely sure on what to put here*)
})
});
but when I tried to use the documents on the index.ejs page, I got a "not defined" result.
And that's it. No sure on how to google this or what should I do.
Thanks!
Try the following:
MyMongoModel.find({}, (err, foundQuotes) => {
if(err) return console.log(err);
res.render('index.ejs', {quotes: foundQuotes});
}
The first argument passed into find(), the {}, will retrieve all database entries matching the particular model, and passes that collection into the callback function (find()'s second argument), as foundQuotes.
In the callback function, index.ejs is rendered (if there are no errors) and foundQuotes is assigned to a variable called quotes. quotes will then be accessible in your index.ejs file.
I have the following basic document in mongo:
connecting to: test
> db.car.find();
{ "_id" : ObjectId("5657c6acf4175001ccfd0ea8"), "make" : "VW" }
I am using express, mongodb native client (not mongoose) and ejs.
collection.find().toArray(function (err, result) {
if (err) {
console.log(err);
} else if (result.length) {
console.log('Found:', result);
mk = result;
console.log('mk = ', mk);
} else {
console.log('No document(s) found with defined "find" criteria!');
}
//Close connection
db.close();
});
}
});
Here is the render code:
// index page
app.get('/', function(req, res) {
res.render('pages/index', { make: result });
});
And i want to pass the data make: VW into my index.ejs file:
<h2>Cars:</h2>
<h3>My favorite make is <%= make %>
This should be real simple and straightforward but i just don't understand how to pass the "mk" variable (which i can console.log to the screen) to be rendered by the ejs view?
You should use the find method inside the route (or with a callback) to get the result and render it:
app.get('/', function(req, res) {
collection.find().toArray(function(err, result) {
if(err) {
console.log(err);
res.status('400').send({error: err});
} else if(result.length) {
console.log('Found:', result);
mk = result;
console.log('mk = ', mk);
res.render('pages/index', {make: mk});
} else {
console.log('No document(s) found with defined "find" criteria!');
res.status('400').send({error: 'No document(s) found'});
}
//Close connection
db.close();
});
});
Very simple, your are outputting an array of JSON objects
Here is one way to visualise it:
[{a:b},{a:b},{a:b},{a:b}];
If you want the first result it would be array[0].a
so you simply need to call it this way:
<%= make[0].(your database key here) =>
//example
<%= make[0].name =>
A more sensible way to get this done would be to iterate through the array and output only the result you want on the server side. If you send all your data to your client you might have security issues depending on what you send.
It should be simple, but you are defining mk just like this: mk = result So because you want to pass a variable to an ejs file you need
"var mk = result"
Have a good day, Ben.