Equivalent of SELECT * in NEDB node.js - javascript

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
});
});

Related

MongoDB Atlas - Create and db from a script

i'm trying to create collection from a script in mongodb, i found on this link a useful script to do that Make a script to create MongoDB collections from Mongo shell? (thanks for that script).
I'm using now this kind of script and it work fine:
db = db.getSiblingDB('emanueledb');
var collectionList = ["collection1", "collection2", "collection3"]
collectionList.forEach(function(collName) {
db.createCollection(collName, {autoIndexId: true});
});
I'm trying to cycle also some db but with this kind of code:
var dblist = ["emanueledb", "db_ema_dv"];
var collectionList = ["ab111", "bc111"];
dblist.forEach(function(dbname) { db.getSiblingDB(dbname)
collectionList.forEach(function(collName) {
db.createCollection(collName, {autoIndexId: true});
})
});
it works but create only the two collection on db_ema_dv. What is wrong?
Is also possible to get collection and db from an external csv to automate everything??
CSV example:
dbname,collectionname
emanueledb,collection1
emanueledb,collection2
testdb,testcollection
Thanks
In the code you posted this expression does nothing (it selects the database but you don't do anything with the database):
db.getSiblingDB(dbname)
Try:
db.getSiblingDB(dbname).createCollection(collName, {autoIndexId: true});
Perfect, thank you! Now works!
var dblist = ["emanueledb", "db_ema_dv"];
var collectionList = ["ab111111", "bc111111"];
dblist.forEach(function(dbname) {
collectionList.forEach(function(collName) {
db.getSiblingDB(dbname).createCollection(collName, {autoIndexId: true});
})
});
as requested before, is possibile to get db and collection from a csv?
CSV Example:
dblist,collectionList
emanueledb,collection1
emanueledb,collection2
testdb,testcollection
To get a database from a .csv you can use the mongoimport command. This will read a CSV file into a collection.

Mongodb does not save a document

I am trying to store some data from an HTML formulary. I send the data using the HTTP POST method and I received them using Express framework in Node.js. The data arrives and it seems to work, but when I try to store them into MongoDB using Mongoose, the database is created but no data is stored when I execute DB.sis_dictionary.find()
I've tried to build different types of schemas and models, but none seems to work. And I get no error from Node.js, it seems to be working, but the MongoDB database does not store anything.
const Mongoose = require('mongoose');
Mongoose.connect('mongodb://localhost:27017/sis_dictionary', {useNewUrlParser: true});
const Schema = Mongoose.Schema;
const wordSchema = new Schema({
word: String
})
const Word = Mongoose.model('Word', wordSchema);
app.post('/saveWord', (req, res) => {
var word = new Word({word: String(req.body)});
word.save(function(err){
if(err) {
return console.error(err);
} else {
console.log("STATUS: WORKING");
}
})
console.log(req.body);
})
server.listen(3000);
console.log("SERVER STARTUP SUCCESS");
In the console, I get the message: "STATUS: WORKING".
sis_ditionary is your DB name and Words should be your collection name. As mongoose automatically creates a plural name for collection from a model if model name not specified when creating from a schema
db.collection.find() is a command to find a collection data when using mongo-shell. Run below command to get data:
use sis_dictionary
db.Words.find()
To beautify result use pretty method
db.Words.find().pretty()
First command will select DB and second command list collection data.
So when you execute db.sis_dictionary.find() it won't work because sis_dictinary is your DB name.
Nodejs way with 'mongoose'
//Model.find({});
Word.find({});
Also, check this line var word = new Word({word: String(req.body)});
What does req.body have? If req.body is {word:"example word"} then you directly pass req.body to modal constructor ie new Word(req.body);
According to your database URL, mongodb://localhost:27017/sis_dictionary, sis_dictionary is the database name.
And according to your mongoose model, Word is your collection name.
When you save a document, it saves under a collection. So you have to make a query under the collections.
So when you try to get data using DB.sis_dictionary.find(), definitely it won't work.
Your query should be like db.collection.find()
Use the following query,
use sis_dictionary
db.words.find()
// for better view
db.words.find().pretty()
For more please check the documentation.
Thank you everybody. You were all right, it was a problem related to my collections names. db.words.find().pretty() worked perfectly!The problem is solved.

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 insert multiple records/rows in MySQL

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.

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