How can i save data in firebase without unique ID? - node.js

I am saving my data in firebase database. But the issue is data saved with auto-increment ID. But i need custom ID. Please guide me how can i achieve this. Below is the output and code. Please check and guide me what can i do.
Data comes like this
I want to display Job1, Job2, Job3..... and so on.
Code
router.get("/firebase/save", (req, res) => {
const ref = firebase.app().database().ref(`levela_jobs`);
ref.remove();
levelConnection.getConnection((err, conn) => {
if (err) throw err;
getJobs(conn)
.then((result) => {
result.forEach((job) => {
var dt = dateTime.create(job.job_created_at);
var formatted = dt.format("f d Y");
const data = {
applications_count: job.count,
job_title: job.job_title,
job_description: stripTags(job.job_description),
created_at: formatted,
};
ref.child(job.job_city).push(data);
});
res.send({ message: "Data saved successfully" }).status(200);
})
.catch((error) => {
res.send(error);
});
});
});
Any solution appreciated!

push() generates a unique id when inserting, use set() instead
as per your case,
use an additional child For eg.
ref.child(job.job_city).child(myId).set(data);

Related

How to take and output documents from a MongoDB database with NodeJS?

I've been working on one of my first API projects with NodeJS, Express and MongoDB. I can save new documents into the database with collection.insertOne(newDocument) method but I can not take existing documents and output them using collection.find({}).
Can you please help me:')
export const visualizeUser = (req, res) => {
console.log("you are searching the user with username " + req.body.username);
users.find({username: 'yavuz'}, (err, data) => {
if(err)
console.log(err);
else
console.log(data);
});
}
thats the code I have written.
MongoInvalidArgumentError: Argument "options" must not be function
and that is the error I am getting.
Your help is really appreciated.
Like error message is saying, you cannot pass function as options argument.
Look here: docs
Your code should look like this:
const visualizeUser = async (req, res) => {
try{
console.log("you are searching the user with username " +
req.body.username);
let data = await users.find({username: 'yavuz'});
console.log(data)
} catch(e) {
console.log(e)
}
}

express.js mongdb its showing data for the wrong call

I am trying to get data from data base for a certain creator or user, but it shows data even if the creator doesn't exists.
this is the code
app.use('/api/places', placesRoutes);
router.get('/user/:uid', placesControllers.getPlacesByUserId);
const getPlacesByUserId = async(req, res, next) => {
console.log("request data!", req.params.uid);
const userId = req.params.uid;
let places;
try {
places = await Place.find({ creater: userId });
} catch (err) {
const error = new HttpError('Something went wrong, could not find a place for the given user.',500);
return next(error);
}
if(!places || places.length === 0){
return next(new HttpError('Could not find a place for the provided userid.',404));
}
res.json({ places: places.map( place => place.toObject({ getters: true }) ) });
};
this the data entry saved in mondo db
{"_id":{"$oid":"62ab10baa6f33b1c588dfb8e"},"title":"ifel tower","description":"big tower","image":"https://pixabay.com/images/search/nature/","address":"Circular Rd, Walled City of Lahore, Lahore, Punjab 54000, Pakistan","location":{"lat":{"$numberDouble":"31.5924979"},"lng":{"$numberDouble":"74.3073198"}},"creator":"u1","__v":{"$numberInt":"0"}}
it should only show data on this url
api/places/user/u1
but it show the same data on different creator id's
data with different url
I think it's related to the typo in the following line:
places = await Place.find({ creater: userId });
I guess creater should be creator instead.

Add an incrementing ID property to each object in array after it has been submitted

I am trying to add a unique ID property to each object in an array after it has been submitted from an input & text area. When I console.log the array as I add more entries it looks like so:
[{"title":"hello","text":"sir"}]
I have two const variables I'm using currently. The contents of the note array get written in to a db.json file.
const notes = [];
const newID = 0;
This is an express js program and below is the function I have to write the input data to the appropriate file. I would like to add an ID for each entry preferably in this function.
app.post("/api/notes", (req, res) => {
let newNote = req.body;
notes.push(newNote)
fs.writeFile(path.join(__dirname, 'db/db.json'), JSON.stringify(notes), (err) => {
if (err) throw err;
});
res.end();
});
I've tried to map the new property unsuccessfully I've also tried a forEach to run through the array to add the id++.
Please let me know if there is any pertinent information I am missing here. Thanks in advance for any help/feedback!
I figured out the forEach and the working code is below.
app.post("/api/notes", (req, res) => {
let newNote = req.body;
notes.push(newNote)
notes.forEach((note, index) => {
note.id = index + 1;
});
fs.writeFile(path.join(__dirname, 'db/db.json'), JSON.stringify(notes), (err) => {
if (err) throw err;
});
res.end();
});

How to update the user object in back4app?

I use Node.js and back4app.com
I try to update the user object. Therefore I have read a lot and found this promissing documentation:
let progressId = "xyz";
let userId = "12354"; //aka objectId
const User = new Parse.User();
const query = new Parse.Query(User);
// Finds the user by its ID
query.get(userId).then((user) => {
// Updates the data we want
user.set('progressId', progressId);
// Saves the user with the updated data
user.save()
.then((response) => {
console.log('Updated user', response);
})
.catch((error) => {
console.error('Error while updating user', error);
});
});
But there also is a warning. It states:
The Parse.User class is secured by default, you are not able to invoke save method unless the Parse.User was obtained using an authenticated method, like logIn, signUp or current
How would this look like in code?
My solution
Well, I got it to work. While I figured it out, I have found some small show stoppers. I list it for anyone it may concern.
Thanks #RamosCharles I added the Master Key in Parse._initialize. Only with that .save(null, {useMasterKey: true}) works. Take notice, without null it also won't work.
That's my working code:
let progressId = "xyz";
const User = Parse.Object.extend('User'); //instead of const User = new Parse.User();
const query = new Parse.Query(User);
query.equalTo("objectId", '123xyz');
query.get(userId).then((userObj) => {
// Updates the data we want
userObj.set('progressId', progressId);
// Saves the user with the updated data
userObj.save(null, {useMasterKey: true}).then((response) => {
console.log('Updated user', response);
}).catch((error) => {
console.error('Error while updating user', error);
});
});
Now I'm wondering
why my working code is different from documentation?
how secure is my code? And what is to do to get it more secure?
Yes, their API Reference is very helpful! On this section, there's a "try on JSFiddle" button, have you already seen that?
To update a user object, you must use the Master Key. On the frontend, it's not recommended, and it's better to create a cloud code function and call it on your frontend. However, for test purposes, you can keep using the API Reference, but on JSFiddle, you need to do some changes, here is their sample code, but with the adjustments:
Parse.serverURL = 'https://parseapi.back4app.com';
Parse._initialize('<your-appID-here>', '<your-JSKey-here>', '<Your-MasterKey-here>');
const MyCustomClass = Parse.Object.extend('User');
const query = new Parse.Query(MyCustomClass);
query.equalTo("objectId", "<object-ID-here>");
query.find({useMasterKey: true}).then((results) => {
if (typeof document !== 'undefined') document.write(`ParseObjects found: ${JSON.stringify(results)}`);
console.log('ParseObjects found:', results);
}, (error) => {
if (typeof document !== 'undefined') document.write(`Error while fetching ParseObjects: ${JSON.stringify(error)}`);
console.error('Error while fetching ParseObjects', error);
});
You'll need to insert the "_" before the "initialize" in your "Parse._initialize" and insert the Master Key in your query as I did on the query.find.

Google Cloud Datastore: lookup and update in one transaction

I'm following the Cloud Datastore sample from the Google documentation as well as the Github sample, following the tasks sample. I'm trying to make a single function call, and mark a task as done by looking it up by the description.
function markDoneByDesc(queryString) {
const query = datastore
.createQuery('Task')
.filter('description', '=', queryString);
var taskKeyId;
datastore
.runQuery(query)
.then(results => {
const tasks = results[0];
console.log('Task found:', tasks[0]);
// I realize there might be multiple tasks with the same desc,
// but I want to update just one for now
taskKeyId = tasks[0][datastore.KEY].id;
console.log('Saving the task Key ID', taskKeyId);
return taskKeyId;
})
.then((taskKeyId) => {
console.log('Calling markDone with task Key ID', taskKeyId);
markDone(taskKeyId); // From the original function in the sample
console.log('Updated task');
})
.catch(err => {
console.error('ERROR:', err);
});
}
Right now, the update doesn't happen :(
I found the solution, thanks to #callmehiphop's help!
Looks like I need to convert the taskKeyId that is returned in the datastore query into an integer, and then pass it to the markDone() function. Otherwise it is passed as a string and the lookup by that ID Key fails.
Here's what the correct code should look like (note the parseInt() in the first return statement):
function markDoneByDesc(queryString) {
const query = datastore
.createQuery('Task')
.filter('description', '=', queryString);
var taskKeyId;
datastore
.runQuery(query)
.then(results => {
const tasks = results[0];
console.log('Task found:', tasks[0]);
// I realize there might be multiple tasks with the same desc,
// but I want to update just one for now
taskKeyId = tasks[0][datastore.KEY].id;
console.log('Saving the task Key ID', taskKeyId);
return parseInt(taskKeyId,10);
})
.then((taskKeyId) => {
console.log('Calling markDone with task Key ID', taskKeyId);
markDone(taskKeyId); // From the original function in the sample
console.log('Updated task');
})
.catch(err => {
console.error('ERROR:', err);
});
}

Resources