How to get return value from Mongoose save function using axios in React JS? - reactjs

I am new to React JS and I created a simple application which accept UserName and Email and inserts to MongoDB.
I use React + Node + Express + Mongoose + MongoDB and I was able to insert the record successfully
DB.js
router.route("/insert").post(function(req, res) {
let comments = new Comments(req.body);
console.log(req.body)
comments.save();
});
App.js
axios.post("http://localhost:4000/insert", {
UserName: username,
UserEmail: email,
Comments: comments
})
Now, I want to return 'numRowsAffected' from DB.js to App.js.
Hence, I modified DB.js by adding callback to mongoose save() function
router.route("/insert").post(function(req, res) {
let comments = new Comments(req.body);
console.log(req.body)
comments.save(function(err, comments, numRows) {
if ( err ) {
res.send(err);
}
else {
res.json({ message: 'Comments added', data: numRows });
}
});
});
However, I don't know how to change the code on App.js (ie in axios.post) to fetch the return value from DB.js
Any help is highly appreciated

You can use Mongoose.update() with upsert option set to true instead of Mongoose.save() and read the nModified and nInserted property of update return value.
You can see this post for more detail.

Related

Passing an object from React to Express and creating a new Airtable record

I’m having trouble passing an object from React to Express, and then creating an airtable record in Express.
In react, i am sending an http request to Express via:
finalSubmit() {
const airtableObj = {
title: 'hi',
}
fetch('api/submit',{
method: 'POST',
body: JSON.stringify(airtableObj),
headers: {"Content-Type": "application/json"}
})
}
My Express code is:
app.post('/api/submit', jsonParser, async (req, res) => {
const newStudy = JSON.stringify(req.body);
await console.log(newStudy);
table.create(newStudy, function(err, record) {
if (err) {console.log(err); res.json(err)} else {console.log(record), res.json('Success!')}
});
})
However, I keep getting errors back from the airtable api. IF I replace the 4th line of my express code with:
table.create({“title”:“hi”}
instead of
table.create(newStudy)
, everything works fine. It seems like this should work according to the airtable documentationt... (https://airtable.com/api). Is there something I am doing wrong with how I am manipulating my data in and out of JSON?
Thanks
This appears to be happening because you're calling JSON.stringify(req.body), which you don't need to do.
table.create takes an object, not a string, so you'll want to do something like this:
const newStudy = req.body;
table.create(newStudy, function(err, record) {
// ...
});
I found a solution, not sure if it's a very good one tho...
app.post('/api/submit', jsonParser, async (req, res) => {
table.create({
"title": `${req.body.post0.title}`} ...

Unable to fetch all values from a branch using Firebase with my AngularJs app

I have the following db structure in Firebase and I intend to grab all values under 'users'. I am receiving an undefined result with the following code:
fetchPharmacists() {
var userid = firebase.auth().currentUser.uid;
return firebase.database().ref().child('users').once('value').then(
function(snapshot) { snapshot.forEach(function(child) {
console.log(child.key+": "+child.val());
});
});
}
Here is the image of my firebase db structure: https://i.stack.imgur.com/HeMg5.png
fetchPharmacists() {
var userid = firebase.auth().currentUser.uid;
return firebase.database().ref().child('/users/' + userid).once('value').then(
function(snapshot) { snapshot.forEach(function(child) {
console.log(child.key+": "+child.val());
});
});
}
I just updated your code. I think you just missed to pass the uid ref. Check the below reference url.
Ref: https://firebase.google.com/docs/database/web/read-and-write
everyone I was able to achieve my intention with AngularFireDatabase using:
this.firebasedb.list("/users").valueChanges()

node express and mssql how do I pass the database query results back to the view template

Been going round in circles for 2 days now.
I am getting some data from Azure SQL database (connection parameters are in sqlconfig)
function getCategories(callback) {
var conn = new mssql.ConnectionPool(sqlconfig);
var req = new mssql.Request(conn);
console.log('in getCategories');
conn.connect((err) => {
if (err) {
console.log('Connection Error:', err);
}
req.query("Select top 3 * from Categories", (err, rs) => {
if (err) {
console.log('Select error: ', err);
} else {
callback(rs.recordsets[0]);
}
conn.close();
});
})
}
I know the data is being returned correctly because when I do
getCategories((rs) => console.log('Get-Categories', rs));
I get the expected results
I am struggling to get the dataset to pass through to the view
app.get('/categories', (req, res) => {
res.render('categories.hbs', {
pageTitle: 'Catgories',
currentYear: new Date().getFullYear(),
categories: getCategories((rs) => rs)
});
});
returns nothing in the categories as it is undefined - so the callback has not finished running when the code is called.
How do I make the app.get wait until the getCategories has completed so that the data is ready to pass back to the view.
I found this post which let me to understand how this works
Need to keep promise result in a variable for Nodejs mssql validation
and have put my own answer in there. Short version is that in Node you have to set the variable value INSIDE the callback stack rather then returning it from the function to assign to the variable.
fetchDataFromDB('Select top 10 * from X', (err, res)=>{myvar = res})
How do I make the app.get wait until the getCategories has completed so that the data is ready to pass back to the view.
You could make the "getCategories" function a middleware that places the result on the request object that can then be obtained by the view. Simply call next() when the operation is complete and then render the view.
app.get('/categories', getCategories, (req, res) => {
res.render('categories.hbs', {
pageTitle: 'Catgories',
currentYear: new Date().getFullYear(),
categories: req.categories
});
});

Update boolean with Mongoose

I have created an app where i can create a to do list. And i have a status that is false when created. The status i supposed to represent if the object done or not.
My mongoose schema look like this in server.js:
// Create mongoose schema
var issueSchema = mongoose.Schema ({
issue: String,
date: String,
status: Boolean,
});
// Create mongoose model
Issue = mongoose.model('Issue', issueSchema);
When i press my button in on my index.html im using angular to send the id trough to the server.js file.
// API PUT ========================
app.put('/issueList/:id', function(req, res){
var id = req.params.id;
Issue.findById(id, function(err, Issue) {
console.log("Object with ID: " + id); // Correct ID
// I need code here
});
});
I need help updating the boolean value to true if false or false if true. Or should i skip the boolean value and use something else?
You can find the issue by id and then save it back to MongoDB after making the changes in success callback.
Issue.findById(id, function(err, issue) {
issue.status = !issue.status;
issue.save(function (err) {
if(err) {
console.error('ERROR!');
}
});
});
I am not sure about the possibility of toggling boolean field atomically as of now in MongoDB.
First, i dont think you should use same variable name outside and inside the function. In this case Issue is same, change it to issue.
And you can try this to update.
Issue.findById(id, function(err, issue) {
console.log("Object with ID: " + id); // Correct ID
issue.status = !issue.status;
issue.save(function(err,result){...});
});
});

Express server stops without throwing error

I am using the angular fullstack generator, but I do not believe this is the problem. I am working with Stripe.js and trying to save the data to the SQLite database using Sequelize. I have tried many different things, but the server stops running when it gets to the part where it is supposed to save the data.
app.post('/register', auth.isAuthenticated(), function(req,res){
console.log('access: ',req.query)
var userId = req.body._id
var data = req.body.data
//create stripe acct for artists
stripe.accounts.create(data, function(err,acct){
if(err){
console.log('err!!! ', err)
} else {
console.log('acct: ', acct)
//look for user in database
db.User.find({
where: {
_id: userId
}
})
.then(function(user) {
if(user){
console.log('user: ', user)
//add stripe acct info to db
console.log('acct:', user.dataValues.account);
/*this is where the Server stops running*/
user.updateAttributes({
account: JSON.stringify(acct)
}).success(function(){
console.log('newacct:', user.dataValues.account);
//just to see if it works
res.send({'account': acct});
})
} else {
console.log('no user found bruh')
}
});
}
})
})
I have tried redirecting, changing req.method to 'get' and then res.redirect. res.end() all of the above, but it always stops running. No errors are thrown it just simply says 'Stopping Express Server'. Thanks in advance for the help!

Resources