Strapi uploaded files are not displaying on website - javascript

I have many files which are stored in upload_file collection in mongodb and they have relations with related content types. However when I open Strapi CMS UI, I cannot see the file attached on its content type.
I am using Strapi v3.4.6 — Community Edition.
In the first picture is showing the my one of upload_file collection item. Its relation is shown in red circle.
In the second picture is showing the my main content type collection item. You see that its id and upload_file rel id is matching.
But in Strapi UI, this file is not linked to model. The file exists in file system of Strapi. However it is not visible
I can add this file manually, but is there any quick way to do this?

You need to migrate the database. We solved with a basic script.
Run http://localhost:3000/migrate
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017";
var dbName = "YOURDBNAME";
const express = require('express')
const app = express()
const port = 3000
var _db;
var _dbo;
var tables = {
"table1": "TabLE1",
"table2": "TABle2",
}
app.get('/migrate', (req, res) => {
res.send('Started!')
_dbo.collection("upload_file").find({}).toArray(function(err, result) {
if (err) throw err;
result.forEach(function (item) {
if (item.related.length > 0) {
var related = item.related[0];
var query = { '_id': related.ref };
var newvalues = { $set: {} };
newvalues.$set[related.field] = item._id;
var tableName = related.kind.toLowerCase();
_dbo.collection(tables[tableName]).updateOne(query, newvalues, function(err, res) {
if (err) throw err;
console.log(res != null ? res.ops : null);
});
}
})
// db.close();
});
})
MongoClient.connect(url, function(err, db) {
if (err) throw err;
_dbo = db.db(dbName);
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
// Run http://localhost:3000/migrate

When uploading your image to strapi make sure your formData has these fields
const formData = new FormData();
formData.append('files', image);
formData.append('ref', 'contentTypeName');
formData.append('refId', dataItemId);
formData.append('field', 'image');

Related

Having some problems trying to call a function from another script

I'm building a mockup website to try and learn NodeJS. I want a login system and I'm trying to connect my register page with my database script. The sql function that sends queries to the database is working as intended, however, when trying to call the query function from the script that manages the register webpage all I get is an error 500.
It would be cool if someone could point me in the right direction, surely it's some quirk from NodeJS I don't know about yet.
Here is my register page script that should call the query function from POST routing:
var express = require('express');
var router = express.Router();
var db = require('../public/javascripts/dbController');
router
.get('/', function(req, res, next) {
res.render('register.html', {title: 'Register'})
})
.post('/', function(req, res, next) {
register(req.body);
res.render('register.html', {title: 'Register'})
})
function register(request)
{
let username = request.login;
let password = request.password;
let sql = "INSERT INTO users (user_username, user_password, user_status) VALUES ('"+username+"','"+password+"', 1);";
console.log("query");
//Why is this not working?
db.query(sql);
}
module.exports = router;
And here is (part of) my dbController script:
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./public/database/db.db', sqlite3.OPEN_READWRITE, (err) => {
if (err && err.code == "SQLITE_CANTOPEN") {
createDatabase();
return;
} else if (err) {
console.log("Getting error " + err);
exit(1);
}
});
//This function is not running when I ask for it in register.js
function query(sql){
console.log("running query: " + sql)
db.all(sql, [], (err, rows) => {
if (err) {
throw err;
}
rows.forEach((row) => {
console.log(row.name);
});
});
}
module.exports = query;
I figure that I probably have to route my scripts through the main app script or maybe I'm exporting wrong? Anyway, any nudge in the right direction would be great because I've been stuck on it a few days. Thanks!
For what I can see, you're indeed importing the "query" function into your "register" page. But you're setting a name of "db" to it.
var db = require('../public/javascripts/dbController');
but you're not exporting "db" you're exporting "query":
module.exports = query;
But that's not really the issue, you could just call it "myRandomNameImport" and it would still work. The problem is that you're accessing a property of "db" that does not exist.
db.query(sql); /* <- db.query does not exist.
* Try db(sql) instead. */
"db" does not have any properties called "query", the function you're trying to use is "db".
function register(request) {
let username = request.login;
let password = request.password;
let sql = "INSERT INTO users (user_username, user_password, user_status) VALUES ('"+username+"','"+password+"', 1);";
console.log("query");
db(sql); /*<- Just call db()*/
}

How to save file paths to my database using Node.js?

I have a simple HTML form that lets the user upload a file. That than gets posted with auth/post/ on submission.
My route looks like this:
const express = require('express');
const authController = require('../controllers/auth');
const router = express.Router();
const multer = require('multer');
function checkFileType(file, cb){
const filetypes = /jpeg|jpg|png|gif|mp3|ogg|aac|wav/;
if (req.fileValidationError) {
return res.send(fileValidationError);
}
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
const mimetype = filetypes.test(file.mimetype);
if(mimetype && extname){
return cb(null,true);
} else {
cb('Format not allowed!');
}
}
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null,'./user_uploads/')
},
fileFilter: function(req, file, cb){
checkFileType(file, cb);
},
filename: function (req, file, cb) {
let ext = file.originalname.substring(file.originalname.lastIndexOf('.'), file.originalname.length);
cb(null, Date.now() + ext)
}
});
const upload = multer({
storage: storage
}).single('user_file');
router.post('/post', upload, function(req, res, next){ res.locals.storage = storage; next();}, authController.post);
module.exports = router;
It checks that you actually put something in, that it's in the right formats, changes the filename and saves it to a temporary folder when you use 'upload'.
I now want to get the storage variable aka the filepath/name/extension to my authController.post.
It's a controller with exports where everything else gets saved to the database. How would I pass the path variable to it?
For reference, it looks like this (I need to put the path into user_path: _______):
exports.post = (req, res, next) => {
let { name, title, cat, con, user_file } = req.body;
const time = new Date().toJSON().slice(0, 19).replace('T', ' ');
let cat_id = 0;
if(req.files) user_file.fileName = req.file.filename;
db.query("SELECT id FROM cat WHERE cat_name = ?", [cat], async function(err, results) {
if (!err)
cat_id = results[0].id;
else
console.log(err);
const ID = await promisify(jwt.verify)(req.cookies.scrooc, process.env.jwtsecret);
const id = ID.id;
db.query('INSERT INTO posts SET ?', {user_id: id, cat_id: cat_id, time: time, title: title, content: con, user_file: res.locals.storage, reply: 0 }, (error, results) => {
if(error)
console.log(error);
else
res.status(200).redirect('/post');
});
});
};
I think you should try writing a textfield (QLineEdit in Python), setting the filename path to the textfield and then saving the content of the textfield to your database using an insert statement during insertion of values into your databse. For example, using Python, here is one way you can achieve that: the getfile is the name of my function, you can name yours anything but remember to call it. The photoinfo is the name of my QLineEdit, in Java, it is called a JTextField if I still remember. So try to use the logic in my code to see if it can resolve yours.
''' def getfile(self):
self.file_name = QtWidgets.QFileDialog.getOpenFileName(None, "Open", "", "All Files (*);;JPG Files(*.jpg)")
try:
if self.file_name[0] != '':
print("success")
self.photoInfo.setText(self.file_name[0])
else:
print("error")
except Exception as e:
print(e)
I ended up just doing the full function in the route. Might not be that clean but it worked.

Code after stored procedure query not being executed in nodejs msnodesqlv8

I'm trying to execute a stored procedure and when I run the code below, the code in the function for the query is not being run at all. There is also no error. I am thinking somehow SQL Server is interpreting the query for the stored procedure incorrectly and stalling because if I use a regular query e.g. select top 1 * from Custom.ExampleTable it works fine.
var express = require('express');
var app = express();
const sql = require("mssql/msnodesqlv8");
// example db connection...
const connectionString = "server=dev\\instance1;database=123456;user=ORG\\NAME;Trusted_Connection=Yes;"
sql.connect(connectionString, err => {
console.log("connected: " + connectionString)
try {
new sql.Request().input('var', sql.VarChar, 2222).execute('dbo.check_ex', (err, results) => {
// code not being run...
console.dir("test")
if (err) {
console.log(err);
}
console.log(rows);
})
} catch (err) {
console.log(err);
}
})
var server = app.listen(5000, function () {
console.log('Server is running..');
});
Output below:
Server is running..
connected: server=dev\\instance1;database=123456;user=ORG\\NAME;Trusted_Connection=Yes;

My mongodb return the array empty []

I'm studying a build full stack JavaScript apps with the MEAN stack, using Node.js, AngularJS, Express and MongoDB.
I'm in the third section where I have to retrieve all the hotels in my database.
When in the browser I type http: // localhost: 3000 / api / hotels /, my database returns an empty array, but the hotel.data.json file is full.
I also tried a copied section5's teacher's final work, but I have the same result, my database is empty [].
This is the code of the hotels.controllers file:
var mongoose = require('mongoose');
var Hotel = mongoose.model('Hotel');
module.exports.hotelsGetAll = function(req, res) {
console.log('GET the hotels');
console.log(req.query);
var offset = 0;
var count = 5;
if (req.query && req.query.offset) {
offset = parseInt(req.query.offset, 10);
}
if (req.query && req.query.count) {
count = parseInt(req.query.count, 10);
}
Hotel
.find()
.skip(offset)
.limit(count)
.exec(function(err, hotels) {
console.log("Found hotels", hotels.length);
res
.json(hotels);
});
};
module.exports.hotelsGetOne = function(req, res) {
var id = req.params.hotelId;
console.log('GET hotelId', id);
Hotel
.findById(id)
.exec(function(err, doc) {
res
.status(200)
.json(doc);
});
};
module.exports.hotelsAddOne = function(req, res) {
console.log("POST new hotel");
var db = dbconn.get();
var collection = db.collection('hotels');
var newHotel;
if (req.body && req.body.name && req.body.stars) {
newHotel = req.body;
newHotel.stars = parseInt(req.body.stars, 10);
collection.insertOne(newHotel, function(err, response) {
console.log("Hotel added", response);
console.log("Hotel added", response.ops);
res
.status(201)
.json(response.ops);
});
// console.log(newHotel);
// res
// .status(200)
// .json(newHotel);
} else {
console.log("Data missing from body");
res
.status(400)
.json({
message: "Required data missing from body"
});
}
};
Thanks for the reply.
This is the file of routes:
var express = require('express');
var router = express.Router();
var ctrlHotels = require('../controllers/hotels.controllers.js');
// Hotel routes
router
.route('/hotels')
.get(ctrlHotels.hotelsGetAll);
router
.route('/hotels/:hotelId')
.get(ctrlHotels.hotelsGetOne);
router
.route('/hotels/new')
.post(ctrlHotels.hotelsAddOne);
module.exports = router;
My console.log() tell:
GET /api/hotels
Requested by: undefined
GET the hotels
{}
(node:2780) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library ins
null
[]
Found hotels 0
I have a hothel-data.json file with all the hotels, the professor in the video at the command prompt when he connects to the db type mongod, but he gave me an error, so when I plug in the db type: mongod --dbpath = data.
I have a main folder, inside I have an API folder with 3 folders inside.
1 CONTROLLERS folder, with hotels-controllers.js, 2 DATA folder with db.js, dbconnection.js, hotel-data.json, hotels.model.js, and 3 ROUTES folder with index.js.
I solved importing the hotel-data.json file, now it's ok, when typing ocalhost: 3000 / api / hotels I see all the hotels.
Thanks anyway.
Aurora

How to use another MongoDB database using Node.js [duplicate]

How do I connect to mongodb with node.js?
I have the node-mongodb-native driver.
There's apparently 0 documentation.
Is it something like this?
var mongo = require('mongodb/lib/mongodb');
var Db= new mongo.Db( dbname, new mongo.Server( 'mongolab.com', 27017, {}), {});
Where do I put the username and the password?
Also how do I insert something?
Thanks.
Per the source:
After connecting:
Db.authenticate(user, password, function(err, res) {
// callback
});
Everyone should use this source link:
http://mongodb.github.com/node-mongodb-native/contents.html
Answer to the question:
var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ReplSetServers = require('mongodb').ReplSetServers,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
GridStore = require('mongodb').GridStore,
Code = require('mongodb').Code,
BSON = require('mongodb').pure().BSON,
assert = require('assert');
var db = new Db('integration_tests', new Server("127.0.0.1", 27017,
{auto_reconnect: false, poolSize: 4}), {w:0, native_parser: false});
// Establish connection to db
db.open(function(err, db) {
assert.equal(null, err);
// Add a user to the database
db.addUser('user', 'name', function(err, result) {
assert.equal(null, err);
// Authenticate
db.authenticate('user', 'name', function(err, result) {
assert.equal(true, result);
db.close();
});
});
});
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
MongoClient.connect('mongodb://'+DATABASEUSERNAME+':'+DATABASEPASSWORD+'#'+DATABASEHOST+':'DATABASEPORT+'/'+DATABASENAME,function(err, db){
if(err)
console.log(err);
else
{
console.log('Mongo Conn....');
}
});
//for local server
//in local server DBPASSWOAD and DBusername not required
MongoClient.connect('mongodb://'+DATABASEHOST+':'+DATABASEPORT+'/'+DATABASENAME,function(err, db){
if(err)
console.log(err);
else
{
console.log('Mongo Conn....');
}
});
I find using a Mongo url handy. I store the URL in an environment variable and use that to configure servers whilst the development version uses a default url with no password.
The URL has the form:
export MONGODB_DATABASE_URL=mongodb://USERNAME:PASSWORD#DBHOST:DBPORT/DBNAME
Code to connect this way:
var DATABASE_URL = process.env.MONGODB_DATABASE_URL || mongodb.DEFAULT_URL;
mongo_connect(DATABASE_URL, mongodb_server_options,
function(err, db) {
if(db && !err) {
console.log("connected to mongodb" + " " + lobby_db);
}
else if(err) {
console.log("NOT connected to mongodb " + err + " " + lobby_db);
}
});
My version:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://user:pass#dhost:port/baseName', function(err, db) {
if (err) {
console.error(err);
}
var collection = db.collection('collectionName');
collection.find().toArray(function(err, docs) {
console.log(docs);
});
});
I recommend mongoskin I just created.
var mongo = require('mongoskin');
var db = mongo.db('admin:pass#localhost/mydb?auto_reconnnect');
db.collection('mycollection').find().toArray(function(err, items){
// do something with items
});
Is mongoskin sync? Nop, it is async.
Here is new may to authenticate from "admin" and then switch to your desired DB for further operations:
var MongoClient = require('mongodb').MongoClient;
var Db = require('mongodb').Db, Server = require('mongodb').Server ,
assert = require('assert');
var user = 'user';
var password = 'password';
MongoClient.connect('mongodb://'+user+':'+password+'#localhost:27017/opsdb',{native_parser:true, authSource:'admin'}, function(err,db){
if(err){
console.log("Auth Failed");
return;
}
console.log("Connected");
db.collection("cols").find({loc:{ $eq: null } }, function(err, docs) {
docs.each(function(err, doc) {
if(doc) {
console.log(doc['_id']);
}
});
});
db.close();
});
This worked for me:
Db.admin().authenticate(user, password, function() {} );
You can do it like this
var db = require('mongo-lite').connect('mongodb://localhost/test')
more details ...
if you continue to have problems with the native driver, you can also check out sleepy mongoose. It's a python REST server that you can simply access with node request to get to your Mongo instance.
http://www.snailinaturtleneck.com/blog/2010/02/22/sleepy-mongoose-a-mongodb-rest-interface/
With the link provided by #mattdlockyer as reference, this worked for me:
var mongo = require('mongodb');
var server = new mongo.Server(host, port, options);
db = new mongo.Db(mydb, server, {fsync:true});
db.open(function(err, db) {
if(!err) {
console.log("Connected to database");
db.authenticate(user, password, function(err, res) {
if(!err) {
console.log("Authenticated");
} else {
console.log("Error in authentication.");
console.log(err);
}
});
} else {
console.log("Error in open().");
console.log(err);
};
});
exports.testMongo = function(req, res){
db.collection( mycollection, function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
Slight typo with Chris' answer.
Db.authenticate(user, password, function({ // callback }));
should be
Db.authenticate(user, password, function(){ // callback } );
Also depending on your mongodb configuration, you may need to connect to admin and auth there first before going to a different database. This will be the case if you don't add a user to the database you're trying to access. Then you can auth via admin and then switch db and then read or write at will.
const { MongoClient } = require('mongodb');
// or as an es module:
// import { MongoClient } from 'mongodb'
// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
// Database Name
const dbName = 'myProject';
async function main() {
// Use connect method to connect to the server
await client.connect();
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('documents');
// the following code examples can be pasted here...
return 'done.';
}
main()
//what to do next
.then(console.log)
//if there is an error
.catch(console.error)
// what to do in the end(function result won't matter here, it will execute always).
.finally(() => client.close());
you can find more in the documentation here: https://mongodb.github.io/node-mongodb-native/4.1/
I'm using Mongoose to connect to mongodb.
Install mongoose npm using following command
npm install mongoose
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/database_name', function(err){
if(err){
console.log('database not connected');
}
});
var Schema = mongoose.Schema;
var userschema = new Schema ({});
var user = mongoose.model('collection_name', userschema);
we can use the queries like this
user.find({},function(err,data){
if(err){
console.log(err);
}
console.log(data);
});

Categories

Resources