I am trying to retrieve the postId
value of the last document created. I retrieved it but I could not find a way to bring that value out of the query. The problem with my code is that the variable that I am querying is trapped inside the promise and I am stuck on finding how to extract it.
exports.postOnePost = (req, res) => {
const first = db
.collection("posts")
.orderBy("createdAt", "desc")
.limit(1)
.get()
.then(function (documentSnapshots) {
const lastPostId = documentSnapshots.docs[
documentSnapshots.docs.length - 1
].get("postId");
console.log(lastPostId); // logs 10257
});
I wanted to take lastPostId
and increment it by one when a new post is added. When I added console.log(lastVisible)
outside the function, it is not defined.
const newPost = {
createdAt: new Date().toISOString(),
postId: lastPostId++, // This does not work
body: req.body.body,
};
db.collection("posts")
.add(newPost)
.then((doc) => {
const resPost = newPost;
resPost.docId = doc.id;
res.json(resPost);
})
.catch((err) => {
res.status(500).json({ error: "something went wrong" });
console.error(err);
});
};
My database documents look like this:
{
body: { stringValue: 'this is my body', valueType: 'stringValue' },
createdAt: {
stringValue: '2020-09-28T15:48:42.903Z',
valueType: 'stringValue'
},
postId: { integerValue: '10257', valueType: 'integerValue' },
}