Trying to read data from Mongo - javascript

so I already have the data in Mongo, but the problem is the Mongo doesn't read properly the data from the backend. This is my backend code:
app.get ('/posts', async (req , res) => {
let db = await connect();
let posts = req.body;
res.send(posts);
});
and the code from services:
async get_posts() {
let response = await Service.get(/posts)
let doc = response.doc;
return {
id: doc._id,
email: doc.email,
title: doc.title,
imageDesc: doc.imageDesc,
img: doc.img,
};
}

You need to use the instance of the db, and an instance to the collection in order to retrieve the posts.
For instance:
app.get ('/posts', async (req , res) => {
const postsCollection = db.collection("posts");
const posts = await postsCollection.find();
return res.json(posts);
});
Read the mongo documentation here

Related

I am connect mongo atlas with this code, but cannot create the database when i send these data

const { MongoClient } = require("mongodb");
const url =
"mongodb+srv://user:password#cluster0.25pjvgx.mongodb.net/products_test?retryWrites=true&w=majority";
const createProduct = async (req, res, next) => {
const newProduct = {
name: req.body.name,
price: req.body.price
};
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db();
const result = db.collection('products').insertOne(newProduct);
} catch (error) {
return res.json({message: 'Could not store data.'});
};
client.close();
res.json(newProduct);
};
const getProducts = async (req, res, next) => {};
exports.createProduct = createProduct;
exports.getProducts = getProducts;
send--
{
"name":"apple",
"price": 99
}
output-
{
"message": "Could not store data."
}
Where is the problem? I try to send the data to the database. But it doesn't work I can not find. please help me.
i used await before db.collection('products').insertOne(newProduct).It works for me

Node.JS: Handling GET and POST request

I'm learning Node.JS and as practise I need to create to endpoints:
GET /albums - Get a list of all albums in the dabatase
POST /purchases - Create a purchase
My attempt is as follows:
const mongoose = require('mongoose');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
// Imports
const Album = require("./models/album");
const Purchase = require("./models/purchase");
// TODO code the API
// Connect to DB
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true});
var conn = mongoose.connection;
conn.on('connected', function() {
console.log('database is connected successfully');
});
conn.on('disconnected',function(){
console.log('database is disconnected successfully');
})
conn.on('error', console.error.bind(console, 'connection error:'));
// Routes
app.get('/albums', function(req, res, next) {
Album.find({}, (err, albums) => {
if (!err) {
res.set({
'Content-Type': 'application/json',
'Status': 200,
})
return res.end(JSON.stringify(albums));
} else {
console.log('Failed to retrieve the Course List: ' + err);
}
});
});
// POST method route
app.post('/purchases', (req, res) => {
const purchase = new Purchase({
user: req.body.user,
album: req.body.album
})
purchase.save(function (err, post) {
if (err) { return err }
res.json(201, purchase);
})
})
module.exports = app;
Instructions for GET Request:
Since this is a JSON API, return JSON and a 200 status code, with the exception of destroy method which should return a 204 status code indicating no content.
All three Album columns title, performer and cost should be returned in a data object for the GET, POST and PUT methods. Here is an example of the format of response.body.data:
Expected Form:
response.body.data = {
_id: "the id of the album",
title: "Appetite for Destruction",
performer: "Guns N' Roses",
cost: 20
};
Instructions for POST Request:
The POST /purchases route should expect user and album properties to be set in the request body. It should then store a reference to both of these records on the newly created purchase record.
The response for POST /purchases should include the purchase record as well as the user and album relations, which should be populated with all their data fields.
Album Schema:
const albumSchema = mongoose.Schema({
performer: String,
title: String,
cost: Number
});
Purchase Schema:
const purchaseSchema = mongoose.Schema({
user: {type: mongoose.Schema.Types.ObjectId, ref: "User"},
album: {type: mongoose.Schema.Types.ObjectId, ref: "Album"}
})
The program need to pass the follwing two test cases for these endpoints:
describe("GET /albums", () => {
it("should return an array of all models", async () => {
const album = new Album(albumData).save();
const res = await chai
.request(app)
.get("/albums")
;
expect(res.status).to.equal(200);
expect(res).to.be.json;
expect(res.body.data).to.be.a("array");
expect(res.body.data.length).to.equal(1);
expect(res.body.data[0].title).to.equal(albumData.title);
expect(res.body.data[0].performer).to.equal(albumData.performer);
expect(res.body.data[0].cost).to.equal(albumData.cost);
}).timeout(2000);
});
describe("POST /purchases", () => {
it("should create a new purchase and return its relations", async () => {
const otherAlbumData = {
title: "Sample",
performer: "Unknown",
cost: 2,
};
const album = await new Album(otherAlbumData).save();
const user = await new User({name: "James"}).save();
const res = await chai
.request(app)
.post("/purchases")
.send({user, album})
;
expect(res.status).to.equal(200);
expect(res).to.be.json;
expect(res.body.data).to.haveOwnProperty("user");
expect(res.body.data.user).to.haveOwnProperty("name");
expect(res.body.data).to.haveOwnProperty("album");
expect(res.body.data.album).to.haveOwnProperty("title");
expect(res.body.data.user.name).to.equal(user.name);
expect(res.body.data.album.title).to.equal(album.title);
}).timeout(2000);
});
});
The problem is that GET /albums doesn't properly fetch the data. Error: "expected undefined to be an array" while POST /purchases throws error 500, "Cannot read property 'user' of undefined" but as per description "route should expect user and album properties to be set in the request body".
Can somebody gives me a headsup? I'm fairly new to Node.JS. Thanks.
you should add following code before Routes:
app.use(express.json({ limit: '15kb' }))
app.use(express.urlencoded({ extended: false }))

Getting error `GaxiosError: TOO_MANY_ATTEMPTS_TRY_LATER` while using identityToolkit.relyingparty.sendVerificationCode in Nodejs

Getting error when calling sendVerificationCode.
Tech Stack Used : Nodejs:
async (req, res, next) => {
// #swagger.tags = ['Auth']
// #swagger.description = ' This endpoint allows to create a post'
const { phoneNumber, recaptchaToken } = req.body;
console.log(recaptchaToken);
const identityToolkit = google.identitytoolkit({
auth: process.env.GCP_API_KEY,
version: 'v3',
});
const response = await identityToolkit.relyingparty.sendVerificationCode({
phoneNumber,
recaptchaToken,
});
// save sessionInfo into db. You will need this to verify the SMS code
req.user.sessionInfo=response.data.sessionInfo;
await req.user.save();
res.status(200).json({success:true,data:"Otp sent"});
}
How to resolve this? I have tried every way I know.

In ExpressJS, how should I call an async function from within a post method?

This posts to the DB successfully:
var express = require("express");
//rest of boilerplate
//the below function posts 'subscribingUserEmail' argument to the DB
async function postToDB(subscribingUserEmail) {
await postEmailToDatabase({
email_address: subscribingUserEmail
});
}
postToDB("example#gmail.com");
app.post("/emailList", function(req, res) {
//nothing yet
});
This does not:
var express = require("express");
//rest of boilerplate
//the below function posts 'subscribingUserEmail' argument to the DB
async function postToDB(subscribingUserEmail) {
await postEmailToDatabase({
email_address: subscribingUserEmail
});
}
app.post("/emailList", function(req, res) {
//call the same function but inside the post method instead
postToDB("example#gmail.com");
});
The difference is where I make the async "postToDB" function call. Is there some way to make this function call from within the post method?
Return the result. This will work assuming postEmailToDatabase is setup correctly in your app
async function runSubscribe(subscribingUserEmail) {
const response = await postEmailToDatabase({email_address: subscribingUserEmail});
return response;
}
app.post("/emailList", async function (req, res) {
//get the email from the frontend's post request
subscribingUserEmail = req.body;
//then pass the email into the top defined function
const result = await runSubscribe(subscribingUserEmail);
// or const result = await postEmailToDatabase({...})
res.send(result)
});
If your req.body has multiple parameters you can deconstruct to keep it clean
{ subscribingUserEmail } = req.body
This is assuming you have that parameter on your body object.
If you don't then you'll need to backup and do
console.log(req.body)

how to move into multiple json objects

i wrote a login page code in js that runs on node express.js server and anyone can put their username /email and password and all that data goes into an json file and it looks like this
{"username":"admin","password":"pasword","email":"user#stackoverflow.com","timestamp":1598668572045,"_id":"dx8HqKkVWe8olH5z"}
i managed to get the timestamp and NeDB gives a random _id to that object.
and when you login you go to a home page that looks like this
but the user gets the username value when there is on object only on the database which is "database.json"
if there is more than 1 object on the database that action will crash and the client can't see his name or any thing it shows nothing .
i don't know how to make it work with several objects on the database.
i thought JSON.parse Or stringfy could make it work but i don't know how to use them on my case.
so here is the js code
var jsonn = '/database.json';
async function userinfo() {
const response = await fetch(jsonn);
const data = await response.json();
var { username, password } = data;
document.getElementById('user').textContent = username;
console.log (data)
console.log (username);
console.log (id);
}
userinfo();
i appreciate any help, if you got any idea please share it with me i really need your help.
UPDATE :
the error message says :
uncaught (in promise) syntaxError : unxpected token in json positon 126.
my server.js code :
const Datastore = require('nedb');
app.listen(2000, () => console.log('listening at 3000'));
app.use(express.static('/public'));
app.use(express.json({
limit: '1mb'
}));
const database = new Datastore('public/database.json');
database.loadDatabase();
app.post('/public', (request, response) => {
const data = request.body;
const timestamp = Date.now();
data.timestamp = timestamp;
database.insert(data);
response.json(data);
console.log(data);
var logdate = new Date;
console.log(logdate);
});
There were some issues with the way that you are calling the DB insert. Basically, on every post request, you allow an insert. This is causing you to have multiple users with the same username. When you search for users by username then you will get a bunch of users. Instead, you want something like the sample code below.
I removed the status public to make it easier to test so make sure to add it back in so you can test front end code. Right now there's just a GET request endpoint so you can get the data by username through a query. This requires more cleanup and checks but at least it will get you started. Also, I remove the password and DB _id from the response as this is probs data you don't want to send back. Ideally, you will encrypt the password before storing it in DB.
const express = require('express');
const app = express();
const Datastore = require('nedb');
app.listen(3000, () => console.log('listening at 3000'));
app.use(express.json({
limit: '1mb'
}));
const database = new Datastore('public/database.json');
database.loadDatabase();
app.get('/public', (req, res) => {
const { username } = req.query;
database.findOne({
username,
}, (err, user) => {
if(err) {
return res.sendStatus(500);
}
delete user._id;
delete user.password;
return res.json(user);
});
});
app.post('/public', (req, res) => {
const data = req.body;
const {
username
} = data;
database.findOne({
username,
}, (err, user) => {
if(err) {
return res.sendStatus(500);
}
if(user) {
delete newUser._id;
delete newUser.password;
return res.json(user)
}
data.timestamp = Date.now();
database.insert(data, (createError, newUser) => {
if(createError) {
return res.sendStatus(500);
}
delete newUser._id;
delete newUser.password;
res.json(newUser);
});
});
});

Categories