How to connect two MongoDb collections? - javascript

I need to know how to add two database collections in MongoDB. Here is my code
async function run2(){
try {
await client.connect();
const itemCollection2 = client.db('warehouse_inventory').collection('myCollection');
// for my items
app.post('/items', async (req, res)=>{
const newItem = req.body;
const result = await itemCollection2.insertOne(newItem);
res.send(result);
})
}
finally {
}
}

to add or create others database just take a const and change collaction name it will be create database automaticely . to use use that const name to your api cursor
async function run2(){
try {
await client.connect();
const otheritemCollection =
client.db('warehouse_inventory').collection('myCollection2');
// for my other db
app.post('/items', async (req, res)=>{
const newItem = req.body;
const result = await otheritemCollection.insertOne(newItem);
res.send(result);
})
}
finally {
}
}

Related

How I can remove only one object in mongodb, not all objects matching the filter query?

This is my code for deleting object containg name as 'bob':
app.delete('/user/:id', async (req, res) => {
const id = req.params.id;
const query = { name: "bob" }
const result = await userCollection.deleteOne(query);
res.send(result);
});
This code delete all objects that have name as 'bob', but I want to delete any one instance only from db matching this query, not all objects. And is there any way to set count that how many instance I want to delete matching this query?
You can use this code
const ObjectId = require("mongodb").ObjectId;
app.delete('/user/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const result = await userCollection.deleteOne(query);
res.send(result);
});

How to automatically calculate INSERTET DATE - current date

i have a table:
CREATE TABLE IF NOT EXISTS bands (
id serial PRIMARY KEY,
name VARCHAR UNIQUE NOT NULL,
creationDate DATE not NULL,
years DATE not NULL
);
I only want to pass name and creation date. what i want is that years will return currentdate - creationDate. The problem is that I do not really know where i should correctly change my code, because im using Node project.
My code looks like this:
const express = require("express");
const app = express();
const pool = require("./db");
app.use(express.json());
// Routes
app.post("/bands", async (req, res) => {
try {
const { name, creationDate } = req.body;
const newBand = await pool.query(
"INSERT INTO bands (name, creationDate,years) VALUES ($1, $2) RETURNING *",
[name, creationDate]
);
res.json(newBand);
} catch (err) {
console.error(err.message);
}
});
app.get("/bands", async (req, res) => {
try {
const allBands = await pool.query("SELECT * FROM bands");
res.json(allBands);
console.log(allBands);
} catch (err) {
console.error(err.message);
}
});
app.get("/bands/:bandsName", async (req, res) => {
console.log(req.params);
const { bandsName } = req.params;
try {
const todo = await pool.query("SELECT * FROM bands WHERE name = $1", [
bandsName,
]);
res.json(todo.rows[0]);
} catch (err) {
console.error(err.message);
}
});
app.put("/bands/:id", async (req, res) => {
try {
const { id } = req.params;
const { name, creationDate } = req.body;
const updateTodo = await pool.query(
"UPDATE band SET name = $1, creationDate = $2 WHERE id = $3",
[name, creationDate, id]
);
res.json("Udało się, zaaktualizowane");
} catch (err) {
console.error(err.message);
}
});
app.delete("/bands/:id", async (req, res) => {
try {
const { id } = req.params;
const deleteTodo = await pool.query("DELETE FROM bands WHERE id = $1", [
id,
]);
res.json("Usunięto");
} catch (err) {
console.error(err.message);
}
});
app.listen(3000, () => {
console.log("server is listening on port 3000");
});
Can anyone tell me where should i change my code so "years" will automatically calculate without me having to put the data in postman?
const { name, creationDate } = req.body;
const d = new Date(creationDate );
const year = d.getFullYear();
Create a date object and retrieve the year would do it

Why is Data not being passed through my Node REST API?

I have the following code.
routes/index.js:
const express = require('express');
const router = express.Router();
const weeklyReportsController = require('../controllers/weeklyReportsController');
router.get('/weekly_reports', weeklyReportsController);
module.exports = router;
controllers/weeklyReportsController.js:
const weeklyReportsService = require('../services/weeklyReportsService');
const weeklyReportsController = async (req, res) => {
try {
const data = await weeklyReportsService;
res.json({data})
console.log('Weekly reports controller - success');
} catch(err) {
console.log(err);
}
};
module.exports = weeklyReportsController;
services/weeklyReportsService.js:
const Pool = require('pg').Pool
const pool = new Pool({connection data})
const weeklyReportsService = async () => {
const res = await pool.query('SELECT * FROM reports', (err, results) => {
if (err) {
throw err;
} else {
console.log('Weekly reports service - success.');
}
return res.status(200).json(results.rows);
});
};
module.exports = weeklyReportsService;
All I am returning by visiting localhost:8080/api/weekly_reports is an empty JSON object of {}. I tried adding some console.log() methods to my code to see what was triggering and what wasn't, and the log from my service is not being set off. I have spent a couple hours trying to dig through example codes, reading documentation, and honestly just looking blankly at my screen - I just can't figure out what I did wrong here.
Does anyone have a suggestion as to what I am doing wrong here?
Thank you all for your time and if there is anything I can add for clarity, please don't hesitate to ask and I will provide it.
Thank you for your help.
EDIT: The data is sitting in a Postgres database called reports with the table also called reports.
There are many things wrong with your approach
Here's how you can achieve what you're trying to do:
controllers/weeklyReportsController.js:
const weeklyReportsController = async (req, res) => {
try {
const data = await weeklyReportsService();
res.status(200).json({data})
console.log('Weekly reports controller - success');
} catch(err) {
console.log(err);
res.status(500).json({error: err.message})
}
};
module.exports = weeklyReportsController;
services/weeklyReportsService.js:
const Pool = require('pg').Pool
const pool = new Pool({connection data})
const weeklyReportsService = () => {
return new Promise((resolve,reject) => {
pool.query('SELECT * FROM reports', (err, results) => {
if (err) reject(err);
console.log('Weekly reports service - success.');
resolve(results.rows)
});
})
};
module.exports = weeklyReportsService;
some links to help you get started:
https://expressjs.com/en/api.html#res
https://developer.mozilla.org/en-US/docs/Glossary/Callback_function
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://stackoverflow.com/a/64052334/2703813
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Cannot findOne by id

Find on Index, return results.
Method:
async index(req,res){
const user = await Usuario.find();
res.json(user);
},
Route:
routes.get('/api/usuarios', Usuario.index);
but findOne({_id}) cannot get results Help pls(i have tryied change params by query, but doesn't works)
method:
async details(req,res){
const { _id } = req.params;
const user = await Usuario.findOne({_id});
res.json(user);
},
route:
routes.get('/api/usuarios.details/', Usuario.details);
First of all you need to change your route
routes.get('/api/usuarios/:_id', Usuario.details);
Then you need to call API like below
http://localhost:<your port number>/api/usuarios/<your id>
Then In your controller
Usuario.findOne(
{ _id: req.params._id }
)
async details(req,res){
const { _id } = req.params;
const user = await Usuario.findOne({_id: _id});
res.json(user);
},
Try the above

Export the particular variable of function to another file

I have a query, that is how I can send "userURL" variable from below file(imageController.js) to another file(contactController.js). and one thing I want to send only "userURL" variable not the whole function "resize". I tried a lot to solve this issue by using "module.exports" but the problem I got is that "module.exports" sending the whole function "resize" not the "userURL" variable. now in second file "contactController.js" where i have mentioned {userURL} in console.log but it's printing only "your result undefined". I just want to export userURL from first file imageController.js to second file "contactController.js".
imageController.js
exports.resize = async (req, res, next) => {
if(!req.file){
next()
return
}
const extension = req.file.mimetype.split('/')[1]
req.body.userFile = `${uuid.v4()}.${extension}`
const photo = await jimp.read(req.file.buffer)
await photo.resize(500, jimp.AUTO)
await photo.write(`./public/uploads/${req.body.userFile}`)
const userimg = photo;
console.log(`./public/uploads/${req.body.userFile}`)
cloudinary.config({
cloud_name: 'katal',
api_key: process.env.API_KEY,
api_secret: process.env.API_SECRET
});
cloudinary.v2.uploader.upload(`./public/uploads/${req.body.userFile}`,{
transformation: { width:100, height:100}}, function(error, result) {
console.log('please show result\t' +JSON.stringify(result))
const userURL ='vikivivki'
res.send(result.secure_url)
console.log(result.secure_url)
})
}
contactController.js
const mongoose = require('mongoose')
const Contact = mongoose.model('Contact')
const moment = require('moment-timezone')
const {userURL} = require('./imageController')
exports.contactForm = (req, res) => {
res.render('contact')
}
exports.usermessage = async(req, res) => {
req.body.name = req.body.name
req.body.email = req.body.email
req.body.message = req.body.message
const ind = moment.tz(Date.now(), "Asia/Calcutta")
const newContact = new Contact(req.body)
await newContact.save()
console.log('your result',userURL)
let showResult1 = JSON.stringify(newContact)
let showResult = JSON.parse(showResult1)
res.send(showResult.message)
}
You need to export items you need access to
exports.userURL ='vikivivki'; //exporting here along with rezise as well
file imageController.js
//imageController.js
exports.userURL ='vikivivki'; //exporting here along with rezise as well
exports.resize = async (req, res, next) => {
if(!req.file){
next()
return
}
const extension = req.file.mimetype.split('/')[1]
req.body.userFile = `${uuid.v4()}.${extension}`
const photo = await jimp.read(req.file.buffer)
await photo.resize(500, jimp.AUTO)
await photo.write(`./public/uploads/${req.body.userFile}`)
const userimg = photo;
console.log(`./public/uploads/${req.body.userFile}`)
cloudinary.config({
cloud_name: 'katal',
api_key: process.env.API_KEY,
api_secret: process.env.API_SECRET
});
cloudinary.v2.uploader.upload(`./public/uploads/${req.body.userFile}`,{
transformation: { width:100, height:100}}, function(error, result) {
console.log('please show result\t' +JSON.stringify(result))
const userURL ='vikivivki'
res.send(result.secure_url)
console.log(result.secure_url)
})
}
In your contactController.js
//contactController.js
const mongoose = require('mongoose')
const Contact = mongoose.model('Contact')
const moment = require('moment-timezone')
const {userURL} = require('./imageController'); // Please have a check on location if they are in the same directory
exports.contactForm = (req, res) => {
res.render('contact')
}
exports.usermessage = async(req, res) => {
req.body.name = req.body.name
req.body.email = req.body.email
req.body.message = req.body.message
const ind = moment.tz(Date.now(), "Asia/Calcutta")
const newContact = new Contact(req.body)
await newContact.save()
console.log('your result',userURL)
let showResult1 = JSON.stringify(newContact)
let showResult = JSON.parse(showResult1)
res.send(showResult.message)
}

Categories

Resources