I am trying to update an existing postgres query in the Nodejs code base.
Below is the existing query to select based on name
constructor(schema){
this.table = schema.employee_tb;
}
row = await this.table.findOne({ name });
Below is the Postgres query I am trying to translate and update the above code into...
select * from table where name = 'john' and '3467' = ANY(group_number)
I tried
row = await this.table.findOne({ name : 'john' && ANY(group_number): '3467' });
For which it is throwing an error.
Basically, I am trying to have the ANY operator in using the massive library.
NOTE: group_number is character_varying[] which has data like {3467, 3455, 3421}..... the query should return the row which contains the group number in the group_number column.
Please help, Thanks in advance.
If you are looking to findOne that has the name 'john' AND the group_number '3467', you need to update your object syntax.
row = await this.table.findOne({ name : 'john', group_number : '3467' });
If you are using Sequelize here for the findOne method, I would take a look at the docs here where you can add in the ANY operator with Op.any in your query, but you will need to have that character_varying[] ready to pass into the function.
This worked!!
row = await this.table.where(`name = 'jhon' and '3467' = ANY(group_number)`);
Related
I'm trying to use the sys.data.createQuery() method that is described in the docs. I have an entity called 'companies' and I'm trying to retrieve all of the companies like this:
var companies = sys.data.createQuery('companies');
But this isn't working, is there another way of getting all of the records of an entity?
You need to execute the query and the iterate over the results like this:
var query = sys.data.createQuery('companies');
// add filters to the query as you want here
var records = sys.data.find(query);
while (records.hasNext()) {
var record = records.next();
sys.logs.info(record.label());
}
So let me start by saying Google's Firebase documentation is horrible. I am trying to append child values to a list stored on a document in Firestore db when a user adds an item to their cart on an eCommerce site. Simplest thing ever (or should be).. All of the documentation says to use .push() and there is not one actionable example of how to implement it. This is not enough for me to understand how to use it:
// Create a new post reference with an auto-generated id
var newPostRef = postListRef.push();
newPostRef.set({
// ...
});
Where does postListRef come from and how do I instantiate a reference that works with .push()? I've been flat out guessing for the last 3 days off and on about how to use the function, from getting the database reference to adding a value. Below are 2 of the ways I have tried to use it. This is such a stupidly simple question and it drives me insane that after hours of googling there is absolutely not one complete example anywhere I could find. Please offer a complete explanation with sample code in what may seem to be an unnecessary level of detail to you on how to implement .push() with firestore in a vanilla javascript front end script! Bonus points if you can explain how to remove a single item from the list as well.
Documentation Links:
https://firebase.google.com/docs/database/web/lists-of-data,
https://firebase.google.com/docs/database/admin/save-data
const db = firebase.firestore();
//set with a function that checks to see if user is logged in
var userUid;
//set if the user is not signed in to persist the cart
var guestUid;
function addItemToCart() {
console.log("Add item to cart triggered..");
const productName = "Assorted Oranges";
const productId = "123";
if (userUid != null) {
var testRef = firebase.firestore().collection('Carts').doc(userUid).push();
testRef.set({
productName: productName,
productId: productId });
} else {
guestUid = getUUID();
var testRef = db.push({
productName: productName,
productId: productId
});
}
}
No matter how I try to use it I keep getting a variation of the error: .push() is not a function like:
product-single:126 Uncaught TypeError: firebase.firestore(...).collection(...).doc(...).push is not a function
at addItemToCart (product-single:126)
The push() method is part of the Firebase Realtime Database API, not of the Firestore API. While both databases are part of Firebase, they each have their own API and are not compatible.
To add a document to a Firestore collection, you'd do something like:
var testRef = firebase.firestore().collection('Carts').doc(userUid);
testRef.set({
productName: productName,
productId: productId
});
firebase snippit
Hello all. I am creating a web app that pulls from a firebase realtime database I have created. Using javascript I would like to pull the data from a specific node (i.e. "8").
I will then use the keys and values from the node in the web app.
What js/firebase code do I need to pull data from any specific node?
Below is the code we have tried. Long term goal is to pull data from a random node, but right now I just to find out how to pull from a specific node. Since the nodes are always going to be a number from 0-49, I don't need to use "length of array" functions when randomizing. I will use "Math.floor(Math.random() * 49" to give me a random number which I can pass into the index value for the node when I figure out how to access one specifically.
ref = firebase.database().ref('articles/');
function setupObservers() {
ref.on('value',function(snapshot){
console.log(snapshot.val())
let articleArray = []
for(key in snapshot.val()) {
let articleKeys = snapshot.val()[key]
articleArray.push(articleKeys)
}
randomArticle(articleArray)
})
}
function randomArticle(articleArray) {
let random = articleArray[Math.floor(Math.random() * articleArray.length)]
console.log(random)
}
setupObservers()
Thanks in advance!!
To read the value from a specific child node of which you know the key, you simply do:
ref = firebase.database().ref('articles');
ref.child("8").on('value',function(snapshot){
console.log(snapshot.val())
});
Hopefully a relatively simple question here with using Firestore querys
I am trying to create essentially a news feed, sorting the newest content from the oldest content. That part is pretty easy, I use:
var first = db.collection("feeds/0/active").orderBy("timestamp", "desc").limit(3);
Which retrieves the 3 newest entries in the news feed. My then idea is in the next query, to pull down the next 3 items in the feed. So if we are going by age, 4,5,6 in the collection in terms of how new the items are.
To do this I grab the last item in query one, and use that node's timestamp as my start at value in query 2:
var first = db.collection("feeds/0/active").orderBy("timestamp", "desc").limit(3);
first.get().then(function (documentSnapshots) {
// Get the last visible document
var lastVisible = documentSnapshots.docs[documentSnapshots.docs.length-1];
var next = db.collection("feeds/0/active").orderBy("timestamp", "desc").startAt(lastVisible.data().timestamp).limit(3);
next.get().then(function(docSn){
console.log("SECOND QUERY!")
docSn.forEach(function(doc) {
console.log(doc.data().message)
})
})
The Result of this code returns the same as the first query returns, the nodes 1, 2, 3 despite trying to tell the second query to start at node3
I also tried passing in a javascript object instead:
var datevalue = Date.parse(lastVisible.data().timestamp)
var next = db.collection("feeds/0/active").orderBy("timestamp", "desc").startAt(datevalue).limit(3);
Which also unfortunately did not work.
I also tried passing in the entire snapshot item, and got the error
"Malforormed Calls from JS: field sizes are different.
[[9,38,38,38],[0,0,1,0],
etc.."
Not really clue where to start with this as I have read through the docs and any examples and I could find and can't seem to figure it out. The only other way I can think of implementing this is by using a Cloud Function to number each node upon creation.. but that feels hacky
Any help would be huge! Thanks
I have a collection called "books" with a field called "created" of type Timestamp. This is not a string. This is not a Date. Please see the Timestamp docs. You need to specify in your settings that you want to use the new Timestamp type instead of Date for your timestamp fields. (See docs for firestore settings)
Example of initiating your firestore and set the TimestampsInSnapshots setting:
var firebaseApp = firebase.initializeApp({
apiKey: [APIKEY],
authDomain: [FIREBASEAPPDOMAIN],
projectId: [PROJECTID]
});
var firestore = firebase.firestore();
var settings = { timestampsInSnapshots: true }; // force Timestamp object instead of Date
firestore.settings(settings);
When this is done, i've run the below code and I get the expected results. First query returns three results. Newest first, latest last.
The second query returns the next three items.
var first = db.collection('books').orderBy("created", "desc").limit(3);
console.log("FIRST QUERY!")
first.get().then(function(documentSnapshots) {
documentSnapshots.forEach(function (doc) {
console.log(doc.data().created.toMillis())
});
// Get the last visible document
var lastVisible = documentSnapshots.docs[documentSnapshots.docs.length - 1];
var next = db.collection('books').orderBy("created", "desc")
.startAfter(lastVisible.data().created).limit(3);
next.get().then(function (docSn) {
console.log("SECOND QUERY!")
docSn.forEach(function (doc) {
console.log(doc.data().created.toMillis())
});
});
});
The console from the above code:
FIRST QUERY!
1540573716371
1540573676652
1540573668643
SECOND QUERY!
1540573658893
1540573536420
1540536647891
Are you checking the entire list returned? Or, just the first node?
If you use startAt, then the first node in the second list will be the last node in the first list (docs). I suggest using startAfter (docs).
Example:
var db = firebase.firestore()
var query = db.collection('feeds/0/active').orderBy('timestamp', 'desc').limit(3)
query.get().then((firstSnapshot) => {
var first3 = snapshot.docs
query.startAfter(first3[2]).get().then((nextSnapshot) => {
var next3 = snapshot.docs
})
})
In my cloud code I want to retrieve the first object in the "Messages" class. Then i want to grab some information from that object, send it to another class, and finally delete that object from the "Messages" class i originally pulled it from.
My question is do i need to query the entire "Messages" class just to get the first object in it? I don't want to slow down my app due to inefficient code.
Parse.Cloud.afterSave("sendMessage", function(Parse.Message, response) {
var body = null;
var senderName = null;
var senderId = null;
var randUsers = [];
var query = new.Parse.Query(Parse.Message);
query.find({
success: function(results){
body.push(results[1].get("messageBody"));
senderName.push(results[1].get("senderName"));
senderId.push(results[1].get("senderId"));
response.success(getUsers);
},
error: funtion(error){
response.error("Error");
}
});
});
to avoid confusion: "getUsers" is an arbitrary function call.
To retrieve entry from class, you need the query the table. However, your problem is getting the first record which does not require getting the all record. From your code I can see that you get the first record of result array (result[1] ). You can apply the solution; getting the first record of the class that you want to query. You can do it via two ways; either you can set the limit 1 to your query or you can use the first() method. The Parse.Query JS API link is below;
https://parse.com/docs/js/symbols/Parse.Query.html
Check the limit and first methods.
Hope this helps.
Regards.