Call schema method without create a new Model object with Nodejs/Mongoose - node.js

My problem is that I want to update a user password that's already stored on MongoDB, and I can't call a method for User. Let me show the code:
User schema:
userSchema = new Schema({ ... });
userSchema.methods.setPassword = function (passwordPlainText) {
this.passwordHash = createHash(passwordPlainText, this.salt);
};
module.exports = mongoose.model('User', userSchema);
And it works fine if I made this:
user = new User();
user.setPassword('foobar');
But if I want to do something like this:
User.findOne({email: req.param('email')}, function (err, user) {
user.setPassword('foobar');
});
It outputs:
TypeError: Object #<Object> has no method 'setPassword'
Can someone please help me to find a way to call these schema methods after retrieving the user from database?
Additional info:
node v0.8.4
express v3.0.4
mongoose module (http://mongoosejs.com/)

Found the problem, seems that the user I was saving in the session didn't persists the schema methods for user. Solved the problem saving just the userId in the session, calling another User.findOne(id) and then calling setPassword method.

Related

Mongoose - Save function does nothing

I'm learning Mongoose, and I got a bug while saving a user. This is my User Model :
This is my route :
The MongoDB connection is correct, I see it in the console, and Postman only shows a Loading Page..
I don't know why it is not working.
Thanks in advance!
I resolved it.
My MongoDB Connection url was :
mongodb://localhost:27017/alexcaron
I've just updated it to
mongodb://localhost/alexcaron
Based on what you explained, and without more logging data, using Mongoose 4.4.12, the word new maybe?
https://github.com/Automattic/mongoose/blob/master/examples/schema/schema.js#L14
var mongoose = require('mongoose'),
User = require('./models/users_model');
For using user:
var user = new User({
courriel: "test1",
password: "test2"
});

Node.js - Express Session, Connect Mongo, and MongoDB

I have a have several mongo databases for separate parts of a website I am making. One of those databases is for sessions. I am using Connect Mongo to store the sessions in the databases. I can't seem to store in to session a ObjectId that references a model I made for a user. But when I read the session I just get the ObjectId I stored and not the object. I already changed stringify to false.
Is it possible to do this with Connect Mongo?
I already tried making a schema and store that schema to a session variable to see if it will give back the user object I have referenced to. I included this code below.
var mongoose = require('mongoose');
var DBsessions = require('../../setup/DBconnect.js').DBsessions;
var QuickChatRefScheme = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
});
module.exports = DBsessions.model('QuickChatRef', QuickChatRefScheme);
And to use this I have:
request.session.allowedChatUser = new QuickChatRef({user:new mongoose.Types.ObjectId(toUser._id)});
Where toUser._id is provided and is a already existing user _id field.
I need the session to ref the user so when node queries the session from the db the user object gets pulled back too.

Mongoose find returns empty array (works fine for other collections)

I have been writing a restful api in nodejs fairly succesfully for the most part. There are two collections in the MongoDB that I am accessing that return empty strings and happen to be the only collections that contain capital letters in their names. When I use MongoClient, I am able to access these collections just fine, so I know that it is not an out of date mongodb driver.
one example is when I try to access a collection called bulkBuds
//bulkBuds model
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var BulkBudsSchema = new Schema({
sourceLicense: String,
quantity: Number,
strainName: String,
priceProfile: String
});
mongoose.model('bulkBuds', BulkBudsSchema);
The controller has a bit of excess logic in the query, but a simple find returns an empty string as well.
//bulkBuds controller
var express = require('express'),
router = express.Router(),
mongoose = require('mongoose'),
BulkBuds = mongoose.model('bulkBuds'),
Friends = mongoose.model('Api'),
config = require('../../config/config'),
jwt = require('express-jwt');
module.exports = function (app) {
app.use('/api/bulkBuds/', router);
};
router.get('/:license', jwt({secret: config.secret}), function (req, res, next) {
if(!req.user.friend){
res.status(401);
}
Friends.findById(req.user.id, function(err, friend){
if(err) throw err;
if(!friend) res.send("friend does not exist");
if(req.user.username != friend.username) res.send("invalid user");
console.log(req.params.license);
console.log(BulkBuds.find({}));
BulkBuds.find({'storeLicense': req.params.license, 'availableForSale': true},
"sourceLicense quantity strainName priceProfile", function (err, bulkBuds) {
if (err) return next(err);
console.log(bulkBuds);
res.send(bulkBuds);
});
})
});
Any suggestions would be greatly appreciated, thanks.
Very difficult to answer without being able to test against your database. But I would try a few things.
refactor {'storeLicense': req.params.license, 'availableForSale': true} to create the object outside of the query, and then console log that object prior to passing it to the query. That will ensure everything is as you expect.
Remove "sourceLicense quantity strainName priceProfile" as the second argument to BulkBuds.find, and replace with an empty object. I usually pass an object as the second param with the following syntax {_id:1,quantity:0} to modify the projection. Your syntax may work, but just in case I would try running the query without to see if that yields any results.
Confirm quantity in your db is indeed a Number and not a String. I know mongoose won't let you insert records that don't validate, not sure about querying. Most likely not the issue, but doesn't hurt to verify.
After creating the Bulkbirds schema try this:
mongoose.model('bulkBuds', BulkBudsSchema, 'bulkBuds');
Another long shot, but perhaps it has something to do with mongoose pluralizing the collection names. Using the above syntax will ensure it's querying the bulkBuds collection.
Once again, difficult to pinpoint without being able to test, but hopefully those ideas help.

Can't find Db in mongodb while using mongoose

The following code, works exactly fine giving the output .
var mongoose=require('mongoose');
var dbUrl='mongodb://localhost:27017/trial1';
mongoose.connect(dbUrl);
//Creating schema
var userSchema=new mongoose.Schema({
name:String,
email:String,
createdOn:Date
});
mongoose.model('User',userSchema);
var User=mongoose.model('User');
var userOne=new User({name:'Mike'});
console.log(userOne.name);
mongoose.connection.on('connected',function(){
console.log('mongoose connected to '+dbUrl);
});
mongoose.connection.close(function(){
console.log('connection closed!!!!');
});
But when I try to search for the db in the connection string (ie)trial1, I am not able to find it, The screen shot is as follows.
Also when I say "use trial1" in mongo shell I'm getting the output as per the following screen shot. Which means the db exists or its been created.
Why am I not able to see that db??
So yes the answer is in the comment of Blakes and also part of answer from Pio.
You don't see the databases because your Mongoose code does not actually create any user in it. When you instantiate your Model User it will create it in memory but not in the database. To insert your user in the database you must call the method save on your instance like this:
var userOne=new User({name:'Mike'});
userOne.save(function(err, user){
if (!err) {
console.log('Now my user is saved in the database');
}
})
So if you don't save your user, then in the mongo shell you won't see the databases as it is empty and so does not exists.
what user you use to access the db, maybe the user have no auth on the db.
or, your db url should be this: mongodb://username:password#localhost:27017/trial1.
thanks.
To display a database with show dbs you need to insert at least one document into one of the db's collection. See more details here.

property model of object mongoose is not a function

I'm using Mongoosejs, with MongoDB and Node.js.
I followed some online tutorials and created myself a test app as below, but keep getting the error message "propert model of object mongoose is not a function.
I dont understand what this means and why its erroring since i followed the online tutorials near enough the same.
Here is my code
// MongoDB test app. Getting to know MongoDB via MongooseJS
var mongoose = require ('mongoose'),
Schema = mongoose.Schema;
//Create Schema
var Storydb = new Schema ({
title: String,
body: String,
date: Date
});
mongoose.connect('mongodb://localhost/test');
//setup model and pass it schema
mongoose.model = ('Storydb',Storydb);
var StoryModel = mongoose.model ('Storydb');
var story = new StoryModel();
//Insert Data
story.title = 'The Man in the green shirt';
story.body = 'once upon a time, way back';
story.date = Date.now();
//save
story.save(function(err){
if (err) {throw err; }
console.log('saved story');
mongoose.disconnect();
});`
I've already tested my MongoDB connection. No issues there, and i am able to insert and retrieve data via the Mongo CLI.
I have also tested my Node.js configuration with basic Hello World examples, and no issues with configuration.
Instead of:
//setup model and pass it schema
mongoose.model = ('Storydb',Storydb);
you should do:
//setup model and pass it schema
mongoose.model('Storydb',Storydb);

Resources