I am attempting to build a basic Vue.js Express profile interface that returns profile info of a specific user based on a route parameter id associated with each user. The .get() request in Vue.js is set up as the following:
created () {
let uri = `http://localhost:3000/users/${this.$route.params.id}`;
this.axios.get(uri).then((response) => {
this.profile = response.data;
});
},
The corresponding GET route in Express.js is set up as the following:
// mongodb
const mongo = require('mongodb').MongoClient;
const url = '...'; // connection url
const usersDB = 'users'; // users db name
app.get('/users/:id', function(req, res) {
let id = req.params.id;
var users;
const findUsers = function(db, callback) {
const collection = db.collection('documents');
// no query filter
collection.find({}).sort( {username: 1} )
.toArray(function(err, docs) {
users = docs;
callback(docs);
});
}
mongo.connect(url, function(err, client) {
// assert.equal(null, err);
const db = client.db(usersDB);
findUsers(db, function() {
// send users
res.status(200).send(users);
client.close();
});
});
});
In the above Express route, I added let id = req.params.id with the intention of prompting this route to respond with specific user info based on req.params.id. I am not sure how to further configure this route to actually return such info based on id. I tried implementing the following in the route:
collection.find({_id: mongo.ObjectId(req.params.id)})
instead of using:
collection.find({}).sort( {username: 1} )
...but that did not work. Any idea how to set up this route to return data based on req.params.id? Thanks!
UPDATED EXPRESS ROUTE
// get all users
app.get('/users/:id', function(req, res) {
var o_id = new mongo.ObjectID(req.params.id))
// get all users
var users;
const findUsers = function(db, callback) {
const collection = db.collection('documents');
// no query filter
collection.find({'_id': o_id})
.toArray(function(err, docs) {
users = docs;
callback(docs);
});
}
mongo.connect(url, function(err, client) {
const db = client.db(usersDB);
findUsers(db, function() {
// send users
res.status(200).send(users);
client.close();
});
});
});
It seems the results aren't returned because of ObjectId comparision not working. Creating new ObjectID using the id from req.params and then doing collection.find should bring back the results
var o_id = new mongo.ObjectID(req.params.id);)
collection.find({'_id': o_id});
Related
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');
Hello i'm trying to fetch some partner names from my mongodb database and put them into a list of variables. But it for some reason loses it's definition when I try to export it. What's going on?
This is the first file.
///// mongodb.js /////
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const findDocuments = function(db, callback) {
// Get the documents collection
const collection = db.collection('partners');
// Find some documents
collection.find({}).toArray(function(err, docs) {
assert.equal(err, null);
callback(docs);
});
};
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'yarle';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected succesfully to Database");
const db = client.db(dbName);
findDocuments(db, function(docs) {
module.exports = {
partner1: console.log(docs[0]['partner_name']),
partner2: console.log(docs[1]['partner_name']),
partner3: console.log(docs[2]['partner_name']),
};
client.close();
});
});
//console.log(Object.keys(partners[0][0]));
And this is the end file.
///// Endfile.ts /////
import { Request, Response } from 'express';
import { PartnersList } from './data.d';
var partners = require( './mongodb.js');
console.log(partners.partner1);
const titles = [
partners.partner1,
partners.partner2,
partners.partner3,
];
Your problem is not with module.exports, it's with asynchronous programming. When you call MongoClient.Connect, the code in your callback does not get executed synchronously. It gets executed some time in the future. You have no control over when that happens.
The same thing is true of the findDocument callback.
Programming asynchronously is a little trickier, but you will have to learn it to write modern javascript. Asynchrony is a central tenet of nodejs. Read on it, learn examples, and your problem will become clear.
Instead of exporting the values of partner1, 2 and 3, export a function with a callback. This new function can call MongoClient.Connect, passing down the callback. Endfile.ts can now call your newly created asynchronous function and assign the titles array in the callback.
Like this:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const findDocuments = function (db, callback) {
// Get the documents collection
const collection = db.collection('partners');
// Find some documents
collection.find({}).toArray(function (err, docs) {
assert.equal(err, null);
callback(docs);
});
};
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'yarle';
module.exports.getPartners = (callback) {
// Use connect method to connect to the server
MongoClient.connect(url, function (err, client) {
if (err) {
callback(err);
return;
}
console.log("Connected succesfully to Database");
const db = client.db(dbName);
findDocuments(db, function (docs) {
const partners = {
partner1: docs[0]['partner_name'],
partner2: docs[1]['partner_name'],
partner3: docs[2]['partner_name']
};
callback(null, partners);
client.close();
});
});
}
and this
import { Request, Response } from 'express';
import { PartnersList } from './data.d';
var mongoClient = require('./mongodb.js');
mongoClient.getPartners(function (err, partners) {
assert.equal(null, err);
const titles = partners;
});
I'm trying to create a REST Service. The route below will execute a stored procedure that will return json results
app.get('/spparam', function (req, res) {
var sql = require("mssql");
// config for your database
var id=0;
var config = {
user: 'username',
password: 'password',
server: 'hostname',
database: 'databasename'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
if(!mylib.isEmptyObject(req.query)){
id=req.query.id;
}else if(!mylib.isEmptyObject(req.params)){
id=req.params["id"];
}
// Executing Stored Prcoedure
request.input('requestid', sql.Int, id)
.execute("Request_Get_ById").then(function(recordSet) {
//console.dir(recordsets);
//console.dir(err);
res.send(recordSet);
sql.close();
}).catch(function(err) {
console.log(err);
});
});
});
I want to minimise my code by creating one route that will handle both query (/spparam?id=1) and params (/spparam/:id/). Is this possible? Is there a better way to handle what I need?
Yup, you can do that with Express like this:
app.get('/spparam/:id?', function (req, res) {
const id = req.params.id || req.query.id;
// the rest of your function, and use id without caring about whether
// it came from params or query
// change order if you want to give preference to query
}
The Express.js docs say it uses path-to-regexp for route matching purposes. There you can see this quote:
Parameters can be suffixed with a question mark (?) to make the
parameter optional.
In javascript, the construct var a = b || c assigns the value of b to a if b is not false-y, and otherwise it assigns the value of c to a.
Every button is clickable and functional before I inserted data.
Render update page after insert:
But then whatever I click the Web got stuck:
But data has already been inserted.
The insert code is here:
var assert = require('assert');
var mongoose = require('mongoose');
var db = mongoose.connection;
// ...
router.post('/update', function (req, res, next) {
var item = {
result: req.body.books
};
db.collection('details-data').insertOne(item, function (err, result) {
db.close();
});
res.render('update');
});
I have a aplication where the user can take some pictures and send to the database, just as simple as that.
Everytime the user login he get a token, if everything fine with the token(he doesn't need to login).
I followed this tutorial to do the jwt authentication, now i want to check on every request except(/login / register) that token and decode it to get the user info ( i am just saving the username, its unique so its fine).
So imagine i am routing to /flower?flowerName (random route) so in this route i want to create a register and save in my database some data, but before that as i said, i should enter a middleware that checks the permission.
This is my middleware:
var jwt = require('jsonwebtoken');
var jwtConfig = require('../config/jwt');
module.exports = function(req, res, next) {
console.log("entered");
// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token || req.headers['x-access-token'];
console.log(req.headers['x-access-token']);
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token,jwtConfig.secret, function (err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
console.log("HEREE");
// if everything is good, save to request for use in other routes
req.decoded = decoded;
console.log(req.decoded);
next();
}
});
} else {
// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
}
my problem is, how can i get the userID for my middleware and then save it in my next route? can i pass it trough the next? like next(userID)????
How can i get the parameter then.
this is where i save the register:
var express = require('express');
var User = require('../models').User;
var Foto = require('../models').Foto;
var router = express.Router();
var jwt = require('jsonwebtoken');
var fs = require('fs');
var fsPath = require('fs-path');
module.exports = {
sendPicture: function (req, res,next) {
var bitmap = new Buffer(req.body.base64, 'base64');
var dummyDate = "25/04/14-15:54:23";
var lat = req.params.lat;
var lon = req.params.lon;
var alt = req.params.alt;
var path = __dirname + "/../public/images/" + req.params.flowerName + "/example3.png";
var fotoPath = ""
var userId = 1;
console.log(lat);
console.log(lon);
console.log(alt);
console.log(req.query.token);
fsPath.writeFile(path, bitmap, function (err) {
if (err) {
console.log(err.stack);
return err;
}
Foto.create({
image: path,
userId: userId
}).then(function () {
return res.status(200).json({ message: "foto created" });
}).catch(function(err){
console.log(err.stack);
})
});
}
}
You should be able to pass any state variables through the whole chain through res.locals, i.e.
res.locals.decoded = decoded;
next();
you can find the details on res.locals here