const signupTime =admin.database.ServerValue.TIMESTAMP
database.ref(`/admin/vendorOrder/${vendor}/${userID}`).set(signupTime);
console.log(signupTime);
i want the time value
while in database it returns correctly
in consol log it returns
how do i make it return value in string
also
database.ref(`/admin/vendorOrder/${vendor}/${userID}/${signupTime}/order`).set(order);
returns error
kindly help
As explained in the doc, with ServerValue.TIMESTAMP you get "a placeholder value for auto-populating the current timestamp as determined by the Firebase servers".
In other words signupTime does not contain the value of the timestamp, since this one is set on the server (the back-end) when you write to the database.
If you want to get this value in your Cloud Function (or in a front-end), you need to query the newly set database node, as follows, for example:
const signupTime = admin.database.ServerValue.TIMESTAMP
const database = admin.database();
const ref = database.ref(`/admin/vendorOrder/${vendor}/${userID}`);
ref
.set(signupTime)
.then(() => {
return ref.get();
})
.then((snap) => {
console.log(snap.val());
})
.catch((error) => {
console.log(error);
});
Related
Please change the value of 'payments._id' to a timestamp. The 'payments._id' object is created by MongoDB when inserting a document into the collection.
onMounted(async () => {
const res = await axios.get("http://127.0.0.1:49146/server/po_payment");
payments.value = res.data;
I'm trying to convert the _id field of a document in a MongoDB collection to a timestamp. I've tried using getTimestamp(), but it does not work. I've seen that it works in the MongoDB shell, but I'm not sure if it can only be used there. I've searched online but I'm still not sure how to do this. Can you suggest a solution?"
onMounted(async () => {
const res = await axios.get("http://127.0.0.1:49146/server/po_payment");
payments.value = res.data;
payments.value.forEach(payment => {
payment.timestamp = new ObjectId(payment._id).getTimestamp();
});
function objectIdToTimestamp(objectId) {
return parseInt(objectId.substring(0, 8), 16);
};
MongoDB uses the first 8 characters to store the timestamp as hexadecimal. You can easily extract that with the function here.
"_id":{"$id":"61b5eb36029b48135465e766"},
"name":"push-ups","link":"https://google.com",
"image":"https://google.com",
"gender":["0","1","2"],
"goal":["lw","gw","sf"],
"age":60,
"excersietype":"chest",
"__v":0
this is how my data is stored in database
and I want to fetch data according to 3 condition
I got 3 queries from front gender goal and age and according to that I have to retrieve data
const gender = req.query.gender;
const age = req.query.age;
const goal = req.query.goal
const level = req.query.level
if (level==='fb'){
const getdata = new Forbeg.find({gender:{$in:gender}},{age:{$lte:age}},{goal:{$in:goal}});
console.log(getdata)
}
Is this a good way to find the data because I am getting error
UnhandledPromiseRejectionWarning: MongooseError: `Model.find()` cannot run without a model as `this`. Make sure you are not calling `new Model.find()`
I am getting above error while fetching
The error is explicit : Make sure you are not calling 'new Model.find()'. Use const getdata = Forbeg.find(...).
However, you will immediately run into the next problem, as Mongoose models return thenables (Promise-like). console.log(getdata) will log Promise<pending>. You need to resolve your database call, either by doing
Forbeg.find(...).then( getdata => console.log(getData));
or (much more better!):
const getdata = await Forbeg.find(...);
console.log(getdata)
Even better, add .lean() to get simple JSON data instead of an array of Mongoose objects (faster), and .exec() to get a true Promise instead of a thenable :
const getdata = await Forbeg.find(...).lean().exec();
console.log(getdata)
Remove new operator
const getData = Forbeg.find({gender:{$in:gender}},{age:{$lte:age}},{goal:{$in:goal}});
Document Reference is used to get document field and its collections from firestore. Following are some examples:
1. Function to read data from field which is having docRef
[Firestore schema]: https://i.stack.imgur.com/pEPK5.png
Here in collection people there is doc named user1 which have a field named hlpr which have docRef for user2 so if i want to access that docRef data i will use following code:
function foo4() {
var user1 = db.collection('people').doc('user1')
user1.get().then((data) => { //get user1 whole doc using get()
var t = data.get('hlpr') //choose field 'hlpr'
t.get().then((doc) => { //get 'hlpr' data() from get()
var user2 = doc.data() //get whole doc from user2
console.log(user2.name) //output field 'name' from user 2
})
})}
2. Read data from array from of docRef. In previous image you can see field named 'cts' which is having array of docRef. Code:
function foo3() { //function to get data from array of docRef
var user1 = db.collection('people').doc('user1'); //choose user1 doc
user1.get().then((doc) => { //get data() of user1 using get()
var contacts = doc.get('cts'); //set var k to field 'cts'
contacts.forEach((data) => { //for each item in array field cts
var userx = data.get(); //read data() using get()
userx.then((doc) => {
var frnd = doc.data(); //set frnd to each data we get from doc
console.log(frnd.name) //output their any field value here i have chosen name
});
});
})}
NOTE: Above code works correctly and you can also use data to put into array also above code might not be best way to get data, but i am a beginner so this is the best i could do.
You can break your code down to a chain of awaits per the comments but a promise chain if processing one item can be fairly clean.
async function foo4() {
var user2 = await db.collection('people').doc('user1').get()
.then(data => data.get('hlpr'))
.then(doc=> doc.data())
.finally(result => result)
.catch(console.log());
you can do some clean code when you nest promise chains.
The second code block has potential errors, if your client exceeds pending 50 documents the client modules will throw errors and fail reads.
I'm trying to retrieve a single document by a field value and then update a field inside it.
When I do .where("uberId", "==",'1234567'), I am getting all the docs with field uberId that matches 1234567.
I know for sure there is only one such document. However, I don't want to use uberId as the document's ID, otherwise I could easily search for the document by ID. Is there another way to search for a single document by a field ID?
So far, reading the docs, I could see this:
const collectionRef = this.db.collection("bars");
const multipleDocumentsSnapshot = await collectionRef.where("uberId", "==",'1234567').get();
Then I suppose I could do const documentSnapshot = documentsSnapshot.docs[0] to get the only existing document ref.
But then I want to update the document with this:
documentSnapshot.set({
happy: true
}, { merge: true })
I'm getting an error Property 'set' does not exist on type 'QueryDocumentSnapshot<DocumentData>'
While you may know for a fact there's only one document with the given uberId value, there is no way for the API to know that. So the API returns the same type for any query: a QuerySnapshot. You will need to loop over the results in that snapshot to get your document. Even when there's only one document, you'll need that loop:
const querySnapshot = await collectionRef.where("uberId", "==",'1234567').get();
querySnapshot.forEach((doc) => {
doc.ref.set(({
happy: true
}, { merge: true })
});
What's missing in your code is the .ref: you can't update a DocumentSnapshot/QueryDocumentSnapshot as it's just a local copy of the data from the database. So you need to call ref on it to get the reference to that document in the database.
async function getUserByEmail(email) {
// Make the initial query
const query = await db.collection('users').where('email', '==', email).get();
if (!query.empty) {
const snapshot = query.docs[0];
const data = snapshot.data();
} else {
// not found
}
}
This always returns an empty array.
<!--
tid - int64
ts - timestamp
url - string
topic - string
msg - string
-->
<script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4.3.1/stitch.js"></script>
<script>
const client = stitch.Stitch.initializeDefaultAppClient("twebh-rufmj");
const db = client
.getServiceClient(stitch.RemoteMongoClient.factory, "mongodb-atlas")
.db("forums");
client.auth
.loginWithCredential(new stitch.AnonymousCredential())
.catch(err => {
console.error(err);
})
.then(displayEmployees);
function displayEmployees() {
db.collection("posts")
.find({}, { limit: 1000 })
.toArray()
.then(docs => {
const html = docs.map(doc => `<div>${doc.topic}</div>`);
document.getElementById("comments").innerHTML = html;
});
}
</script>
<div id="comments"></div>
I expect the returned topic to be "test" as that's what I have for a record in the database. I tried lots of different example code from the MongoDB wiki, but this returns no errors in Chrome's console, yet I don't get a returned value.
I think the reason you are not getting any value from your db query is because there is slight issue with your find query.
You are passing limit :1000 as the second argument of find query, but it should be the third argument. Second argument is supposed to be the projection, and third argument is the query options(where limit is passed)
You need to pass empty object as second argument and {limit:1000} as the third argument.
Also, it would be better if you do a .join() after map, so that it returns a string instead of an array to innerHTML
Try this :
function displayEmployees() {
db.collection("posts")
.find({}, {}, { limit: 1000 })
.toArray()
.then(docs => {
const html = docs.map(doc => `<div>${doc.topic}</div>`).join('');
document.getElementById("comments").innerHTML = html;
});
}