How to retrieve data under multiple query parameters using mongodb and javascript - javascript

I am learning to use mongodb and javascript to send requests to a database. I am provided an example for a single parameter query. How could I modify this to take 4 or 5 parameters?
console.log(req.query);
const filter = req.query._id === undefined
? {}
: { _id: req.query._id };
users.findUsers(filter, '', 0)
.then(user => {
console.log(user)
res.send(user);
})
.catch(error => {
console.error(error);
res.send({ error: 'Request failed' });
});
});```

Related

I am trying to use the mongodb client for js to validate if a db exists in the db before other actions. What would be the best way to use it?

Here is the code snippet I am using where sourceUri is the connection string, nsfrom is the db. How do I block the rest of the code until I get console.log (`Database "${nsFrom}" exists.`);
MongoClient(sourceUri, { useUnifiedTopology: true },function (err, sourceMongoClient){
const sourceAdminDb = sourceMongoClient.db(nsFrom);
sourceAdminDb.admin().listDatabases((err, result) => {
if (err) throw err;
console.log(result);
const sourceDbExists = result.databases.some(sourceAdminDb => sourceAdminDb.name === nsFrom);
if (sourceDbExists){
console.log (`Database "${nsFrom}" exists.`);
}
else{
console.log (`Database "${nsFrom}" doesn't exist.`);
}
})
})

recursive calls in Javascript API (Promises)

I am trying to fetch data from one MongoDB collection and with that result, I am passing that value into another function to get the data from GridFS files for same id.
router.get('/employee/:id', async(req,res) =>{
let gID = req.params.id;
var getUser = await User.find({id:gID});
//console.log(res);
console.log(getUser);
if(getUser){
try{
gfs.files.find({objectID:getUser.id}).toArray(async (err, files) => {
if (!files || files.length === 0) {
res.send({
message: "No User Found",
});
} else {
res.send({
message: "data fetched",
data: getUser,
image: files
});
}
});
}catch(err){
res.send({
message:err.code,
data:err
});
}
}else{
res.send({
message:"error in getting the data",
});
}
})
I tried of this but I am not able to get the expected result, I am getting the user information from getUser but I am not able to fetch the file tagged with that user from GridFS. Can anyone tell me where I am lagging and how could I correct this.

Storing JSON objects in the postgreSQL using parameterized query

I am having problems with saving JSON objects in the database using parameterized queries. I am using postman to send this object on red.body
enter image description here
On my server side I havet his code:
queryController.createQuery = (req, res, next) => {
const { info }= req.body;
const sqlQuery = 'INSERT INTO test (info) VALUES ($1) RETURNING *';
db.query(sqlQuery, [info])
.then(result => {
console.log(result);
if (result) res.locals.message = "Saved the query successfully";
next();
})
.catch(err => {
return next({
log: `queryController.createQuery: ERROR: ${typeof err === 'object' ? JSON.stringify(err) : err}`,
message: { err: 'Error occurred in queryController.createQuery. Check server log for more details.'},
})
})
Why is that I still get this error: enter image description here
throw new TypeError('Client was passed a null or undefined query')
^
TypeError: Client was passed a null or undefined query
Here is my table schema:
CREATE TABLE test (
id serial NOT NULL PRIMARY KEY,
info json NOT NULL
);
How do I format $1 correctly to get it accept it as JSON file?
Query example:
EXECUTE 'INSERT INTO test (info) VALUES ($1) RETURNING *' USING '[{"size": "Small", "quantity": 1, "product_id": 1}]'::jsonb;

TypeError : Cannot read property 'create' of undefined. using sequelize for adding and entry registering a user

I am getting this error when I call this controller, Seems like they can't recognize .create method of the model,
How to import sequelize so that I can use it
const db = require("../Models/m_user");
const M_user = db.m_user;
exports.registerUser = (req, res) => {
if (!req.body.user_id) {
res.status(400).send({
message: "Content can not be empty!"
});
return;
}
// Register a user
const user = {
User_ID: req.body.user_id,
User_Password: req.body.user_password
};
// Save User in the DB
M_user.create(user)
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while injection"
});
});
};
It seems to me that your m_user is stored in the db variable - that what your import line suggests. So you are trying to access m_user.m_user?

How to add conditional checks over ORM (sequelizejs) queries?

Suppose i have a table gameData {gameId, currentBoardLayout}, a get request like www.chess.com/asd123 is sent over to the server, where asd123 is my game id, I need to catch this id (asd123 which is my gameId) and check for it in my table (gameData) and implement the following logic :
srv.get('/:id', (req, res) => {
if ( gameData.findAll({where: {gameId: req.params.id} )
{ // Game room found
return currentBoardLayout
}
else
{ error : Invalid game id }
})
How can I achieve this?
Thanks
You can use Sequelize's findById method.
srv.get('/:id', (req, res) => {
gameData.findById(req.params.id)
.then(result => {
res.send(result)
})
.catch(() => {
res.send({
error: 'Could not find ID'
})
})
})
Here's what is happening:
Sequelize's findById method will return a promise. If it successful, you will get your item from the database back. If the item cannot be found, the catch method will fire.
res.send is Express' way of sending data back to the client.
It is worth checking out the Sequelize docs:
Using models
Querying

Categories

Resources