how to find the latest document in mongo db using moongoose - reactjs

Iam trying to store a list of product ids in an array in database and retrieve the latest array.
this is my server side code
router.post("/scannedproducts",async(request,response)=>{
console.log(request.body)
const Scannedproducts = new scannedproducts({
ids:request.body
})
Scannedproducts.save()
console.log(Scannedproducts)
const getLatestProduct =await scannedproducts.find().sort({ createdAt: -1 }).limit(1) // 10 latest docs
console.log(getLatestProduct)
})
but it consolelogs an empty array of ids.
please help...

The mistake in your code is you should have used await while calling the save() method
Solution should be :
router.post("/scannedproducts",async(request,response)=>{
const Scannedproducts = new scannedproducts({
ids:req.body
})
await Scannedproducts.save()
console.log(Scannedproducts)
const getLatestProduct =await scannedproducts.find().sort({ createdAt:-1 }).limit(1) // 10 latest docs
console.log(getLatestProduct)
})
it would fix your issue,
But anyways You should have provided the scannedProducts model in your question, and assigning the whole request body object to a property is a bad practice. you should take an ids array as user input and store it in server
i would suggest you to write your code as:
router.post("/scannedproducts",async(request,response)=>{
const Scannedproducts = new scannedproducts({
ids:req.body.ids
})
await Scannedproducts.save()
console.log(Scannedproducts)
const getLatestProduct =await scannedproducts.find().sort({ createdAt:-1 }).limit(1) // 10 latest docs
console.log(getLatestProduct)
})
Thank you

Related

I want to update firebase database with react

I have a problem while trying to update data in the firebase database with my react code.
Most probably my code syntax is not good, so can you help me in some way?
This is my code syntax:
const addNewData = async (e) => {
e.preventDefault();
let data = {
sifra:sifraRef.current.value,
naziv:nazivRef.current.value,
detalji_dijete:detaljiRef.current.value,
opis:opisRef.current.value,
broj_obroka:brojObrokaRef.current.value,
napomena:napomenaRef.current.value
}
const uuid = uid();
await updateDoc(collection(db, `namirnice/${uuid}`), data)
close();
}
All these examples I saw on youtube tutorials works...
I hope you can help me.
The updateDoc function is used to update an existing document. But since you call uuid(), you always get a new value and so you're trying to update a document that doesn't exist yet, which isn't possible.
To create a new document, use setDoc instead of updateDoc in your code.
Also see the Firebase documentation on setting a document

Accessing the collection inside a document of a parent collection in firestore

I am looking to fetch the data of collection named users which has documents with an id of logged-in users' uid. Further, these documents contain some data and a subCollection called posts.
which looks like -
So now, I need to fetch all four(4) of these documents along with the posts collection data together so that I can display it.
My approach -
( here I fetched the document ids - middle section of image IDs)
// Fetching Firestore Users Document IDs
const [userDocs, setUserDocs] = React.useState([]);
React.useEffect(() => {
try {
const data = firestore.collection('users')
.onSnapshot(snap => {
let docIDs = [];
snap.forEach(doc => {
docIDs.push({id: doc.id});
});
setUserDocs(docIDs);
})
}
catch(err) {
console.log(err);
}
}, [])
Now, I have tried to fetch the entire data using the following way (which isn't working)
// Fetching Firestore Posts Data
const [postData, setPostData] = useState([]);
React.useEffect(() => {
try {
userDocs.map(data => {
const data = firestore.collection('users/'+currentUser.uid+'/posts')
.onSnapshot(snap => {
let documents = [];
snap.forEach(doc => {
documents.push({...doc.data(), id: doc.id});
});
setPostData(documents);
})
})
}
catch(err) {
console.log(err);
}
}, [])
Finally, I should end up with postData array which I can map on my card component to render all posted images and captions to the UI.
I am not sure if this is the right way to achieve what I am doing here, please help me correct this error and if there's a more subtle and easy way to do it please let me know. Thank You.
I have tried to fetch the entire data
Looking at the code you wrote for fetching "the entire data" (i.e. the second snippet) it seems that you don't need to link a post document to the parent user document when fetching the post documents. In other words, I understand that you want to fetch all the posts collection independently of the user documents.
Therefore you could use a Collection Group query.
If you need, for each post document returned by the Collection Group query, to get the parent user doc (for example to display the author name) you can do as explained in this SO answer, i.e. using the parent properties.

Select data from firebase via id gives me a CORS error

I'm deleting data from my firebase db with fetch but I can't figure out how to point to an exact ID.
const deleteHandler = async (id) => {
console.log(id);
await fetch(
`https://react-task-tracker-8e519-default-rtdb.firebaseio.com/tasks.json/${id}`,
{
method: "DELETE",
}
);
I tried it this way, but it gives me a CORS error.
I'm also displaying data from this db, that works fine.
UPDATE: I also want to say that when i console.log the id it gives me the correct one.
(Tl;dr: Try adding '.json' to the end of the endpoint.)
I would recommend reading this page to get a general understanding of what a CORS error is and why it might be happening.
In your case, I would recommend using the Firebase SDK that is best suited to your application. You could start here and follow the setup instructions for whichever is most applicable to your use case (perhaps the node client sdk)?
If you must avoid using the sdks for some reason then I would refer to some other Stackoverflow questions such as this one, which suggests that all Firebase REST endpoints need to end with '.json'.
You just need to add .json at the end of your request and remove .json from tasks.json. like this:-
await fetch(
`https://react-task-tracker-8e519-default-rtdb.firebaseio.com/tasks/${id}.json`,
const deleteHandler = async (id) => {
console.log(id);
await fetch(
`https://react-task-tracker-8e519-default-rtdb.firebaseio.com/tasks/${id}.json`,
{
method: "DELETE",
}
);
Just replace .json text with ${id}.json.
Have a nice day

MongoDB Webhook function to save forminput in database

I've been trying to save data from my form in my MongoDB for some time.
I also get a response from the database.
See also: create object in mongo db api onclick sending form
Unfortunately there are not enough tutorials in my mother tongue and I don't seem to understand everything in English.
I've tried some of the documentation, but I always fail.
What is missing in my webhook function so that the form data can be stored?
exports = function(payload) {
const mongodb = context.services.get("mongodb-atlas");
const mycollection = mongodb.db("created_notifications").collection("dpvn_collection");
return mycollection.find({}).limit(10).toArray();
};
The Webhookfunction was totally wrong.
READ THE DOCUMENTATION FIRST
exports = function(payload, response) {
const mongodb = context.services.get("mongodb-atlas");
const requestLogs = mongodb.db("created_notifications").collection("dpvn_collection");
requestLogs.insertOne({
body: EJSON.parse(payload.body.text()),
query: payload.query
}).then(result => {
})
};

Firestore Snapshot Read only last document

fire.firestore().collection('Customer').get()
.then(data=>{
data.docs.forEach(doc=>{
let db = fire.firestore().collection(`Customer`)
db.where("updated", ">=", 0).limit(100).onSnapshot(async doc=>{
try {
await doc.docs.map(each=>{
setDatas([...datas, {...each.data()}])
})
}
})
})
I am trying to append the object in the array to query from firestore.
However, somehow it only reads last document.
Please help me if you could store state without using array.
Checking your code and running this data as sample I could notice your code is getting all the results and not just the last one, so there could be something else. Also it seems like a double unnecessary query.
Instead you can query all the docs you may want to get them using .. where("updated", ">=", 0).limit(100) .. and not a query inside a query.
You can use the sample code from here to make something more simpler:
const admin = require('firebase-admin');
admin.initializeApp();
let db = admin.firestore();
const citiesRef = db.collection('Customer');
const snapshot = await citiesRef.where('updated', '>=', 100).limit(100).get();
if (snapshot.empty) {
console.log('No matching documents.');
return;
}
snapshot.forEach(doc => {
//Your code here to add to your array
});
This code is for NodeJS but you can adapt it to ReactJS

Resources