How do I access methods attached to a Schema in mongoose - node.js

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*/

Related

How to check the collection is exist using MongoJS and 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.

is it possible to create an instance for an existing model in sails js as below?

var userModel = new User();
userModel.email = req.body.email;
userModel.password = req.body.password;
userModel.save(function(err, user) {
.........
}
Actually i have a model named 'User' and i have to create instance for that to store its attributes temporarily and save it as encapsulated object. But it's showing error from my controller like following..
throw message;
^
TypeError: object is not a function
Is it possible to create like this?
Try to use the model.create() function. Documentation Wateline Model.Create

Loopback Context is found null in model beforeCreate when using Mocha

I have a model that access context object (to get currentUser) in beforeCreate.
myModel.beforeCreate = function(next, md) {
var Category = md.app.models.Category;
var ctx = loopback.getCurrentContext();
var currentUser = ctx && ctx.get('currentUser');
...
});
It works when I normally access it from explorer but when I try to access it using mocha in unit test
I get error because currentUser is not set.
So, when I try to set currentUser, I don't get context object in tests.
var ctx = loopback.getCurrentContext();
if (ctx) console.log("CTX exists");
here ctx is null.
Please suggest where I have gone wrong.
Cheers
Raj
I think if you use the loopback-testing module you'll have success more easily here. Specifically the givenLoggedInUser function creates a user for your test and logs that user in, creating a saved token as well.
var lt = require('loopback-testing');
var credentials = { email: 'user#example.com', password: 'pwd' }
lt.givenLoggedInUser(credentials, 'user');
it('should have a logged in user', function (done) {
if (loopback.getCurrentContext()) {
console.log("CTX exists", this.user);
}
});
This should also create the current context you need. Take a look at the rest middleware tests for more help here: https://github.com/strongloop/loopback/blob/master/test/rest.middleware.test.js#L128

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.

Mongoose.model vs Connection.model vs Model.model

I am bit confused with usage of models in mongoosejs
Models can be created using mongoose in these ways
Using Mongoose
var mongoose = require('mongoose');
var Actor = mongoose.model('Actor', new Schema({ name: String }));
Using Connection
var mongoose = require('mongoose');
var db = mongoose.createConnection(..);
db.model('Venue', new Schema(..));
var Ticket = db.model('Ticket', new Schema(..));
var Venue = db.model('Venue');
Using existing Model instance
var doc = new Tank;
doc.model('User').findById(id, callback);
Now what is the difference between model returned by Mongoose.model , Connection.model and Model.model. and when to use what ,
what is the recommended way to create/fetch model ?
mongoose.model ties the defined model to the default connection that was created by calling mongoose.connect.
db.model ties the model to the connection that was created by calling var db = mongoose.createConnection.
doc.model looks up another model by name using the connection that doc's model is tied to.
All three can be sensibly used in the same program; which one to use just depends on the situation.
ok here is what I found
Important! If you opened a separate connection using
mongoose.createConnection() but attempt to access the model through
mongoose.model('ModelName') it will not work as expected since it is
not hooked up to an active db connection. In this case access your
model through the connection you created:
var conn = mongoose.createConnection('your connection string');
var MyModel = conn.model('ModelName', schema);
var m = new MyModel;
m.save() // works
vs
var conn = mongoose.createConnection('your connection string');
var MyModel = mongoose.model('ModelName', schema);
var m = new MyModel;
m.save() // does not work b/c the default connection object was never connected
mongoose.connect is for you connect to same database,although your database is balance or replicaSet
db.model is for multiple connections open to Mongo, each with different read/write settings

Resources