How to check the collection is exist using MongoJS and Node.js - node.js

I need to check if the collection is exist in the DB using Node.js and MongoDB. Here I am using mongoJS as node driver. My code is below:
var mongoJs=require('mongojs');
var md5 = require('md5');
var dateTime = require('node-datetime');
var collections=['f_users'];
var MONGOLAB_URI="mongodb://user:*****123%40#ds127153.mlab.com:27153/fgdp";
var db=mongoJs(MONGOLAB_URI,collections);
exports.userSignup=function(req,res){
var email=req.body.email;
var password=req.body.password;
var dob=req.body.dob;
var dt = dateTime.create();
var createdDate=dt.format('Y-m-d H:M:S');
var updateDate=dt.format('Y-m-d H:M:S');
db.f_user_login
db.f_user_login.insert()
}
Here I need if collection f_user_login exist inside db or not. If not exist it will insert the required document.

I suppose that you first need to add the collection to your db.
var db=mongoJs(MONGOLAB_URI,['f_user_login', 'f_users']);
And then you can try running this
var fUserLoginExist = db.f_user_login.findOne();
if (fUserLoginExist) {
// the collection exists
} else {
// the collection does not exist
}
Hope it helps

When I wish to check an existence of collection, I use an easy piece of code below
var nmColl = "MyCollection";
if(db.getCollectionNames().find(function(el) {return el == nmColl;}) == null)
{
//do something
}
It is good for MongoDB up 3.0. At first, there is function db.getCollectionNames() to return all exists collections, when I look up specified name of collection. If there is no necessary collection, for example, I will create it.

Related

How do I access methods attached to a Schema in mongoose

I am experiencing some confusion regarding calling a method that I have attached to a schema in a project that I am working on. I am essentially accessing a document from the database and trying to compare the hashed password I have stored to the password that was submitted by the user on login. When I go to try and compare the password though, the method that I attached to the methods object of the schema is nowhere to be found. It doesn't even throw an error for me telling me that there is no such method. This is where I am setting the method on the schema:
var Schema = mongoose.Schema;
var vendorSchema = new Schema({
//Schema properties
});
vendorSchema.pre('save', utils.hashPassword);
vendorSchema.methods.verifyPassword = utils.verifyPassword;
module.exports = mongoose.model('Vendor', vendorSchema);
The function I am using as the compare method is a utility function that I created called verifyPassword, which is held in a utility file. The code for that function is here:
verifyPassword: function (submittedPassword) {
var savedPassword = this.password;
return bcrypt.compareAsync(submittedPassword, savedPassword);
}
I try to verify the password like this:
var password = req.body.password;
_findVendor(query)
.then(function (vendor) {
return vendor.verifyPassword(password);
});
I have promisified mongoose with bluebird promises if that makes any difference. I have tried a lot of things, but can't find any answer as to why nothing is happening when I try to invoke this method that I thought I had attached the schema. Any help would be greatly appreciated.
/*VendorSchema.js*/
var Schema = mongoose.Schema;
var vendorSchema = new Schema({
//Schema properties
});
vendorSchema.methods.method1= function{
//Some function definition
};
vendorSchema.statics.method2 = function{
//Some function definition
};
module.exports = mongoose.model('Vendor', vendorSchema);
Lets say i would like to access VendorSchema inside other file:
/*anotherfile.js*/
var VendorSchema= require('../VendorSchema.js');
var Vendor = new VendorSchema();
As we defined method2 as static you can access method2 inside anotherfile.js by using schemareference object VendorSchema.
VendorSchema.method2
But method1 is not static you can access method1 inside anotherfile.js using only after creating object instance of schema.
Vendor.method1 /*Vendor is object instance of the schema*/

Creating a JSON file(MongoDb Collection) of User Info for a Node.js application that uses Bcrypt and passport for login

I'll try and word this question as short and clear as possible. I have a node.js project that connects to a non local instance of MongoDB using mongoose. I have written code for a user to login using passport module. I create a JSON file as a users collection. When I go to sign in I get this error
throw "Not a valid BCrypt hash."
So If I wanted to just create a JSON file of Users to work with this how would I go about it? My end goal is to convert RDBMS to MongoDB. Just starting with the users table. I understand that if I was registering new users I could just make a function that would hash their password like
newUser.password= createHash(password)
var createHash = function(password){
return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null);
}
or something along those lines. Summary: How do I make a JSON file of user info for MongoDB that'll work with bcrypt hash and passport?
var fs = require('fs');
var bc = require('bcrypt-nodejs')
fs.readFile('users.txt',function(err,data){
var x = [];
if(err) throw err;
var buf = new Buffer(data);
x = buf.toString();
x = JSON.parse(x);
//console.log(x);
for(var a in x){
x[a].password=createHash(x[a].password);
}
x = JSON.stringify(x);
fs.writeFile('users.txt',x,callback()); //or just push directly to db?
});
var createHash = function(password){
return bc.hashSync(password, bc.genSaltSync(10), null);
}
function callback(){
console.log('finished');
}
Just read in my User Info , Bcrypted the passwords and made a new file. Put it in Mongo. Hopefully this helps someone else. If anyone has a better solution for me I'd appreciate it.

How to retrieve all settings with OrmLiteAppSettings in one call?

I'm using the TextFileSettings and OrmLiteAppSettings together via MultiAppSettings, but would prefer to pre-read all the database settings in one call versus on demand, is there a way to do that, so that everything is in memory?
Below is the relevant code:
OracleDialect.Provider.NamingStrategy = new OrmLiteNamingStrategyBase();
OracleDialect.Provider.StringSerializer = new JsonStringSerializer();
var fileSettings = new TextFileSettings(ConfigUtils.GetAppSetting("PathToSecuredFile"));
var dbFactory = new OrmLiteConnectionFactory(fileSettings.GetString("LeadDbConfigKey"), OracleOrmLiteDialectProvider.Instance);
var dbSettings = new OrmLiteAppSettings(dbFactory);
var multiSettings = new MultiAppSettings(fileSettings, dbSettings);
container.Register<IAppSettings>(c => multiSettings);
Thank you,
Stephen
To preload all db App Settings you can just read the entire ConfigSetting db table into a .NET Dictionary and wrap it in DictionarySettings, e.g:
using (db = dbFactory.Open())
{
var allDbSettings = db.Dictionary<string,string>(
db.From<ConfigSetting>().Select(x => new { x.Id, x.Value}));
var multiSettings = new MultiAppSettings(
fileSettings,
new DictionarySettings(allDbSettings));
}

sharing db connection across entire app in mongoose

With the latest mongoose update, you can no longer user models the way I've been doing. I need to share the same db connection across my entire app.
https://github.com/LearnBoost/mongoose/issues/1249
Here is the old way which no longer works:
./models/user.js
var mongoose = require('mongoose'), cfg = require('../config')
, Schema = mongoose.Schema
, db = mongoose.createConnection(cfg.mongo.uri, cfg.mongo.db);
...
module.exports = db.model('Item', ItemSchema);
How can I re-use db connection as suggested in github issue above?
I'm using var User = require('./models/user'); in several different places in my code base.
Option 1: Use a shared object
My model code looks similar, but instead of repeatedly requiring the modules I just require them once when the application starts and then assign the results to a shared object. For example if you are using an express app you could just so something like app.locals.models.User = require('./models/user');. Then anything with access to the app can see your models without needing a require.
Option 2: Ensure a single modification in the exported function
You can define your user module like so:
var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({name: String});
var User = null;
module.exports = function(db) {
if (db && User === null) {
User = db.model('User', userSchema);
}
return User;
};
When you start your application you simply need to: require('./models/user')(db). Subsequent requires by other modules in your application can drop the db paramater, as User will only be set once.

Apache Thrift with nodejs example

I am trying to use Apache Thrift for passing messages between applications implemented in different languages. It is not necessarily used as RPC, but more for serializing/deserializing messages.
One application is in node.js. I am trying to figure out how Apache thrift works with node.js, but I can't find too much documentation and examples, except for one tiny one regarding Cassandra at:
https://github.com/apache/thrift/tree/trunk/lib/nodejs
Again, I don't need any procedures declared in the .thrift file, I only need to serialize a simple data structure like:
struct Notification {
1: string subject,
2: string message
}
Can anyone help me with an example?
I finally found the answer to this question, after wasting a lot of time just by looking at the library for nodejs.
//SERIALIZATION:
var buffer = new Buffer(notification);
var transport = new thrift.TFramedTransport(buffer);
var binaryProt = new thrift.TBinaryProtocol(transport);
notification.write(binaryProt);
At this point, the byte array can be found in the transport.outBuffers field:
var byteArray = transport.outBuffers;
For deserialization:
var tTransport = new thrift.TFramedTransport(byteArray);
var tProtocol = new thrift.TBinaryProtocol(tTransport);
var receivedNotif = new notification_type.Notification();
receivedNotif.read(tProtocol);
Also the following lines need to be added to the index.js file from the nodejs library for thrift:
exports.TFramedTransport = require('./transport').TFramedTransport;
exports.TBufferedTransport = require('./transport').TBufferedTransport;
exports.TBinaryProtocol = require('./protocol').TBinaryProtocol;
Plus there is also at least one bug in the nodejs library.
The above answer is wrong, because it tries to use outBuffers directly, which is an array of buffers. Here is a working example of using thrift with nodejs:
var util = require('util');
var thrift = require('thrift');
var Notification = require('./gen-nodejs/notification_types.js').Notification;
var TFramedTransport = require('thrift/lib/thrift/transport').TFramedTransport;
var TBufferedTransport = require('thrift/lib/thrift/transport').TBufferedTransport;
var TBinaryProtocol = require('thrift/lib/thrift/protocol').TBinaryProtocol;
var transport = new TFramedTransport(null, function(byteArray) {
// Flush puts a 4-byte header, which needs to be parsed/sliced.
byteArray = byteArray.slice(4);
// DESERIALIZATION:
var tTransport = new TFramedTransport(byteArray);
var tProtocol = new TBinaryProtocol(tTransport);
var receivedNotification = new Notification();
receivedUser.read(tProtocol);
console.log(util.inspect(receivedNotification, false, null));
});
var binaryProt = new TBinaryProtocol(transport);
// SERIALIZATION:
var notification = new Notification({"subject":"AAAA"});
console.log(util.inspect(notification, false, null));
notification.write(binaryProt);
transport.flush();
DigitalGhost is right, the previous example is wrong.
IMHO the outBuffers is a private property to the transport class and should not be accessed.

Resources