How to get a mongodb query to frontend code - javascript

I'm trying to query a MongoDB database and then display it to the frontend code/page.
Here's what I got so far. Note, it does sucessfully console.log() the search results on the backend just not on the frontend.
Backend File
export async function searching() {
let output = "";
const mongo = require('mongodb').MongoClient
const url = "mongodb+srv://[protected..]";
await mongo.connect(url, {useNewUrlParser: true,useUnifiedTopology: true}, (err, client) => {
const db = client.db('domains')
const collection = db.collection('domains')
collection.find().toArray((err_again, items) => {
output = items
console.log(output)
return output
})
})
}
Frontend
export async function button2_click(event) {
let output = await searching()
console.log(output)
}
Note I'm doing this in Wix code so some of the synctax front-end syntax might be different.
The "console.log(output)" gets an undefined response.
When I console log the backend file the "console.log(output)" successfully outputs the array, but it's now showing on the frontend console.
Please help I've been spending hours on this with no luck. THANK YOU!

I was able to figure this out so I figured I would post the answer here:
export async function findRecord(database, sub_db, query) {
let output = "";
const mongo = require('mongodb').MongoClient
const url = "mongodb+srv://...";
const client = await mongo.connect(url, {useNewUrlParser: true,useUnifiedTopology: true});
const db = client.db(database)
const collection = db.collection(sub_db)
const items = await collection.find(query).toArray();
client.close()
return items;
}

Related

Work with Stellar Network : How can I check the balance for each account using node.js and mongo.db

``I workk with stellar network , I create an account with stellar laboratry and node.js,in the begin I save the data in Json file and everything works perfectly but now I want to save it into the database, the signup function work correctly but when I try to check the balance account I am bloked and I have Errors
So my question : I want to use the publickey from the user_account in the database and check the balance using Stellar Horizen
How can I do it ?``
enter image description here
This is the data for the user when he sign up
**SignUp function **
const userModel= require('../models/user.model')
const { errorsSignUp,errorsSignIn } = require('../utils/errors')
const stellar = require("stellar-sdk");
module.exports.signUp= async(req,res)={
const {pseudo,email,password}= req.body
try{
const pair = stellar.Keypair.random();
const userData= await userModel.create(
{
pseudo,
email,
password,
publicKey: pair.publicKey(),
secret:pair.secret(),
})
// await userData.save()
res.send(userData)
res.status(201).json({userData:userData._id})`
}
catch(err){
const errors= errorsSignUp(err)
res.status(200).send({errors})
}
}
Check balance function
const stellar= require('stellar-sdk')
const accounts= require("./accounts")
const util = require("util")
//const userModel = require('../models/user.model')
// function without mongodb
// saving data in file.json
var server= new stellar.Server("https://horizon-testnet.stellar.org")
const checkAccount= async accounts={
const AccountsBalance= await Promise.all(
accounts.map(async account= await server.loadAccount(account.publicKey)))
return AccountsBalance.map(({id,balances})=({
id,
balances,
}))
}
checkAccount(accounts)
.then(account=
console.log(util.inspect(account,false, null))
)
.catch(error={
console.log(error)
})

MySQL NodeJS not getting latest data after write

I am having trouble figuring out the problem to an issue where when I write data (create, update, delete) then write a query to get the data after, the data that I receive back is the data prior to the write.
For example:
Let's say I have two functions createApple() and getAppleById. I have a utility function called getConnection() that gets a connection from a pool to be used for transactional queries. I have an endpoint that creates an apple and I get back to the insertId from mysql then I use that to get the apple but when I return it as a response, I get an empty object.
const createApple = async ({ type }) => {
const connection = await getConnection();
await connection.beginTransaction();
return await connection.query(`INSERT INTO apple (type) VALUES (?)`, [type]);
}
const getAppleById = async (appleId) => {
const connection = await getConnection();
return await connection.query(`SELECT * FROM apple WHERE id = ?`, [appleId]);
}
router.post(`/api/apples`, async (req, res) => {
const { insertId: createdAppleId } = await createApple({ ...req.body });
const apple = await getAppleById(createdAppleId);
res.status(201).send(apple); // <-- this returns {}
});
I noticed that if I add a console.log() before sending the data back, it does get back the data, for example:
router.post(`/api/apples`, async (req, res) => {
const { insertId: createdAppleId } = await createApple({ ...req.body });
const apple = await getAppleById(createdAppleId);
console.log(apple);
res.status(201).send(apple); // <-- this now returns the newly created apple
});
Any ideas on why this may be happening? Also, is this considered a good way of getting a newly created/updated entity or would it be better to make two separate calls:
First call to create/edit the entity (a POST or PATCH call)
Second call to get the entity (a GET call)
Any help is appreciated!
Thanks!
const createApple = async ({ type }) => {
const connection = await getConnection();
await connection.beginTransaction();
await connection.query(`INSERT INTO apple (type) VALUES (?)`, [type]);
await connection.commit();
}
I think error this function when you use transaction, you should commit or rollback transaction after finish query
This is best practice for me, I hope it useful for you
const createApple = async ({ type }) => {
const connection = await getConnection();
await connection.beginTransaction();
try{
await connection.query(`INSERT INTO apple (type) VALUES (?)`, [type]);
await connection.commit();
}catch{
await connection.rollback()
}
}

Iterate through all documents in a MongoDB collection and saving the data in array

I thought this would be a straightforward task but what I am trying to do is go through all the documents (users) in my collection using a cursor and saving some data into a JS array or set about a specific field of the user or all of the data on that user. I am able to see each document printed on the console, but after looping through all the documents, my array is still empty when printed. Where am I going wrong and if there is an alternative approach please let me know.
const mongoose = require('mongoose');
let Users = require('./models/user.model');
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex:true, useUnifiedTopology: true});
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB connection success");
})
let arr = [];
async function getRecords() {
let cursor = Users.find({}).cursor();
for (let doc = await cursor.next(); doc != null; doc = await cursor.next()) {
arr.push(doc); //does not work :(
console.log(doc); //this works
}
}
getRecords();
console.log("ARRAY:",arr); //prints []
Suggestion
Your code should read as such
let arr = [];
// This is an async function (returns a promise)
async function getRecords() {
let docs = await Users.find({}).lean();
arr = docs.filter((doc) => doc !== null); // As an example, however, enter appropriate condition for filter
return arr;
}
// Call the async funtion
getRecords().then(docs => {
console.log("ARRAY:", arr);
});

Axios and mongoose to build an API

Can I use axios and mongoose to build an API? That's because I am new in the back-end developement, so I tried and I gotta an error like below, I was trying to do an API with axios and mongoose, but I don't know if i can use them together, I was kind to test this code to see if they work, but apparently not. So any suggestion to code better or is that correct what I am doing, is there other way ? I sure there is, but which recommendion you guys can make.
I want to create two separate files, one for controllers like "product.controller" and use my api to do all the requests that my differents controllers could need
Error: socket hang up
at createHangUpError (_http_client.js:323:15)
at Socket.socketOnEnd (_http_client.js:426:23)
at Socket.emit (events.js:203:15)
at endReadableNT (_stream_readable.js:1145:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
product.controller.js
const Product = require('../models/product.model');
const api = require('../api/api');
mongoose = require('mongoose').set('debug', true);
// To create a new Product
exports.create = async (req, res) => {
const product = await api.create('/product', req.body);
res.status(201).send({ message: 'The product has been created successfully !', product });
};
api.js
const axios = require('axios');
const baseURL = require('../config/database');
const list = async(key) =>{
const content = await axios.get(baseURL.local.urlDataBase + key +'.json')
if(content.data){
const objects = Object
.keys(content.data)
.map(key=>{
return{
id: key,
...content.data[key]
}
})
return objects
}
return []
}
const get = async(key, id) => {
const content = await axios.get(`${baseURL.local.urlDataBase}/${key}/${id}.json`)
return {
id: id,
...content.data
}
}
const create = async(key, data) =>{
await axios.post(`${baseURL.local.urlDataBase}/${key}.json`, data)
return true
}
module.exports = {
list, create
}

How do I seed mongodb with data from an external API?

I'm trying to learn NodeJS. I'm using mongoose & mLab. I'm new to every one of these technologies.
My model at the moment looks like this. I will add a few things to the schema later.
const mongoose = require("mongoose");
const fetchData = require("../seed");
const schema = mongoose.Schema;
const dataSchema = new Schema({});
module.exports = recallData = mongoose.model("recalls", dataSchema);
I also made a seed file for fetching data..
const Recall = require("./models/Recall");
module.exports = function getData(req, res) {
const urls = [url1, url2, url3];
urls.map(url => {
fetch(url)
.then(res => res.json())
.then(data =>
data.results.map(recalls => {
let recs = new Recall(recalls);
recs.save;
})
);
});
}
my question is how do I make the fetch run and populate the database? Is there a command or a mongoose function that will do that?
I know that I'm basically trying to emulate Rails with a seed file. Maybe it's not the way to do it in Node. Any help is super appreciated.
Turns out it's pretty simple. All I needed was a nights sleep. I needed to connect to mongoose and after save(), disconnect.
Now the code looks like this. I still need to add and edit some stuffs in it. Any smart refactoring advice is appreciated.
const mongoose = require("mongoose");
const Recall = require("./models/Recall");
const db = require("./config/keys").mongoURI;
const fetch = require("node-fetch");
const URLS = require("./config/seedURLs");
let resultData;
let saveCounter = 0;
mongoose
.connect(db)
.then(() => console.log("mongodb connection success"))
.catch(error => console.log(error));
URLS.map(async url => {
try {
const response = await fetch(url);
const json = await response.json();
resultData = [...json.results];
for (let i = 0; i < resultData.length; i++) {
let temp = new Recall({
key1: resultData[i].key1,
key2: resultData[i].key2,
.
.
.
});
temp.save(() => {
saveCounter++;
if (saveCounter === resultData.length) {
mongoose
.disconnect()
.then(() => console.log("mongodb disconnected"))
.catch(error => console.log(error));
}
});
}
} catch (error) {
console.log(error);
}
});
Run node seed.js command.
This is the general idea.

Categories

Resources