How to insert multiple records/rows in MySQL - javascript

Is it possible in Sails.js to insert multiple records?
I am using MySQL, I need to save 'n' rows into MySQL depending upon request coming from API.
I need help with respect to Sails.js
Thank you

Yes you can write multiple records in mysql at once.
let my model is:
module.exports = {
tableName:'test',
autoCreatedAt:false,
autoUpdatedAt:false,
attributes: {
name:'string'
}
};
First let's see how is it done in mysql query.
INSERT INTO `test` VALUES (1,'AB'),(2,'ABCCDC');
Now this is how you can add multiple records...
Test.create([{name:'name1'},{name:'name2'},{name:'name3'}])
.exec(function(err,done){
if(err){
//hendle the error;
return;
}
//successfully inserted;
});
Now i guess my point is clear.
you just have to pass the array of objects in model.create() to insert multiple objects.

Related

Query the last record in supabase?

How to check the last record of a user in supabase. I would only need by means of the user ID to find his last record "date" in a descending way
I have something like the following, but this would just sort the table and I really don't want to bring it all just the most recent dates. I am working on this in nodejs with express and I am using the #supabase/supabase-js library for auth with supabase
Does anyone know how?
const { data, error } = await supabase.from('activity-historic-tracked').select('*').in('user_id', user_ids).order('date', { ascending: false })
I made the query in supabase using sql with DISTINC ON to return only different values because I only want to list the different values and not bring repeated values and at the end ordering them descendingly
select distinct on (user_id) user_id, date
from "activity-historic-tracked"
order by user_id, date desc;
According to what I was reading in this question rpc function, doing something like this could be done using views or supabase stored procedures, but how is it done?
Please help me
As mentioned in the other SO answer you linked, you can create a view or a rpc function. To create a view you would use the SQL editor in the Supabase Dashboard with the following:
CREATE VIEW view_name AS
SELECT DISTINCT on (user_id) user_id, date
FROM "activity-historic-tracked"
ORDER BY user_id, date DESC;
And now you would use this with the supabase-js library just like you would with a normal table.
await supabase.from('view_name').select('*')
If you were to go the .rpc function route, you would call it via that method on the supabase-js library.

How to validate data so no incorrect data is saved to the database, using javascript

I would like to validate my code for adding a product to sqlite database, but dont know how I do that in the best way. I have been using this:
routes.post('/product/', async (req, res)
and await for adding a product to the sqlite database, which was successful.
What I would like to accomplish is to check so the same product can't be added twice. Do you have any tips for how I can do that?
I was thinking if I could use an if statement to check that..
When you create your sqlite table, add a statement something like this to create a unique index (an index that prohibits duplicate values) on your table.
You can also add this index onto an existing table.
CREATE UNIQUE INDEX product_indx ON yourtable(product);
Then, attempts to insert duplicate values of product will fail and throw an error.
You can catch the error and use it to whine at your user, or present whatever error message is appropriate
One option is to get all the product from the db inside routes.post('/product/', async (req, res) and compare it with the request

Equivalent of SELECT * in NEDB node.js

I am new on nedb using node.js just wondering how to display all records or SELECT * FROM tablename i know that nedb is completely different from mysql but i need to embed a database inside my electron application, i just need to know if nedb is capable of db queries like mysql can do.
The code below able me to find a single records i just want to display all records.
var Datastrore = require('nedb');
var db = new Datastrore({filename: 'guitars.db'});
db.loadDatabase(function(err){
db.find({year : 1990}, function (err,docs){ console.log(docs); });
});
Just use
db.loadDatabase(function(err){
db.find({}, function (err,docs){
console.log(docs);//all docs
});
});

Firebase Database workouts issues

I created the Database in firebase and used for my hybrid application, Let you explain the application scenarios below.
I have a hybrid application in this app, We need to insert, update, delete, kind of operations using firebase.
As of now, I did the insert method kind of queries alone using code. So the thing is I want to create multiple tables in firebase is it possible ?
Because For example, I've userTable, adminTable and guestTable, So If I need to insert one userData before that I need to check already the user found or not in Admin table this kind of scenarios How can I do in firebase ?
How can I maintain multiple tables in the firebase Database dashboard?
I have the table name called "Inmate_Data" now I want to add one more Table called "Admin_Data" and How can I do a joint operation like connecting two table using Firebase.
And, I tried to add one more table using Import JSON option But while I inserting new JSON the old Table got deleted like the "Inmate_Data" deleted and new JSON got added.
Please guide me in this.
#FrankvanPuffelen - Please find the below coding part.
Actually, I created the form and saving the data into firebase using below code.
$scope.addInmateDataToFirebase = function() {
alert('Firebase')
var newPostKey = null;
// Get a key for a new Post.
newPostKey = firebase.database().ref().child('Tables/Inmate_Data').push().key;
alert(newPostKey);
var dateofjoin= $filter('date')($scope.IMDOJ, 'yyyy-MM-dd');
var dateofbirth= $filter('date')($scope.IMDOB, 'yyyy-MM-dd');
console.log("Result"+ newPostKey);
var admissionId="KAS"+pad(newPostKey,5);
console.log("Padded number"+ pad(newPostKey,5));
alert(admissionId);
// A post entry.
var postInmateData = {
Inmate_ID: admissionId,
Inmate_Name: $scope.IMfirstnameText,
Inmate_Perm_Address1: $scope.IMAddress1 ,
Inmate_Perm_Address2: $scope.IMAddress2 ,
Inmate_Perm_City: $scope.IMCity,
Inmate_Perm_State: $scope.IMState,
Inmate_Perm_Pincode: $scope.IMPincode,
Inmate_ProfilePhotoPath: $scope.IMProfilePhotoPath,
Inmate_Temp_Address1: $scope.IMLocAddress1,
Inmate_Temp_Address2: $scope.IMLocalAddress2,
Inmate_Temp_City:$scope.IMGcity,
Inmate_Temp_State: $scope.IMGstate,
Inmate_Temp_Pincode: $scope.IMGpincode,
Inmate_Mobile: $scope.IMMobile,
Inmate_DOB: dateofbirth,
Inmate_EmpOrStudent: $scope.IMEmpStudent,
Inmate_DOJ: dateofjoin,
Inmate_ID_Type: $scope.IMIdcardType,
Inmate_ID_No: $scope.IMIdcardno,
Inmate_ProffPhotoPath: $scope.IMProofPhotoPath,
Inmate_Status:$scope.IMStatus
};
// Write the new post's data simultaneously in the list.
var updates = {};
updates['/Tables/Inmate_Data/' + newPostKey] = postInmateData;
return firebase.database().ref().update(updates).then(function() {
//$scope.ClearInMateDetails();
alert(admissionId);
$scope.statusMessage = "Welcome to Kasthuri Hostel. Your Admission ID is" + admissionId +" . Enjoy your Stay.";
//sendSMS('9488627377',$scope.statusMessage);
alert('Inmate data stored in cloud!');
$scope.ClearInMateDetails();
}, function(error) {
alert (error);
});
}
Now the Inmate_data got stored. and I need to save the Inmate_alloc_data into firebase but before that, I need to check whether the Inmate_Id available in the Inmate_Data table in firebase.
Please find the below snap :
My suggestions :
For example like above screenshot now I've multiple tables like "Inmate_Data", "Inmate_Alloc", and more Shall I get all the data and store it in a local SQLite Db like same as "Inmate_Alloc_tbl" and "Inmate_Data_tbl" and finally If I update any values finally I want to get all values in the local database and store it in the firebase. Is it possible to handle ?
If so I can manage lots of SQL queries, right ? Because via firebase we can't able to manage all queries right ?
Please suggest your ideas.

How to store values in MONGO DB using JAVA?

I want to make a blog post in my web application. Initially I was using mysql as DB. In which i will get the post entered in the text area of blog as an object in JS and send that object to java server side. There I will write mysql query and get the object in resultset and save in database. But now i want to use mongoDB for the same. I am able to understand the basic stuff through many tutorials which I learnt. But I am unable to implement that in my application. I want to know how the object that comes from the JS will be sent inside the loop and how I should query to save the object also similarly if I need to send a object from server side to JS. How should i do.?
My Server side code:
public DB MongoConnection(Blog blog) throws UnknownHostException, MongoException{
Mongo m = new Mongo("localhost" , 27017); //mongo object
DB db = m.getDB("myblog");
System.out.println("Connected");
//making a collection object which is table when compared to sql
DBCollection items = db.getCollection("items");
System.out.println("items got");
//to work with document we need basicDbObject
BasicDBObject query = new BasicDBObject();
System.out.println("Created mongoObject");
//Cursor, which is like rs in sql
DBCursor cursor = items.find();
System.out.println("items got");
while(cursor.hasNext()){
System.out.println(cursor.next());
}
In the above code i understood everything such as how a mongo connection, documents, collections and cursor's work. Now how should i save the value coming as an object from JS and save in mongoDB. Any Suggestions Please?
Use method save of DBCollection class something like that:
while(cursor.hasNext()){
DBObject doc = cursor.next();
doc.put("name", "Leo-vin");
items.save(doc);
}
method cursor.next() returns object of type DBObject. It is your BSONObject.
Update:
to modify document (BSON) use method put of class BSONObject

Categories