registration in node.js using passport - javascript

I got User is not defined error with this code.
var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/user');
router.post('/api/signup', function(req, res) {
if (!req.body.name || !req.body.email || !req.body.password) {
res.json({success: false, msg: 'Please fill all fields!'});
} else {
var newUser = new User({
name : req.body.name,
email : req.body.email,
password : req.body.password
});
// create the user
newUser.addUser(function(err) {
if (err) {
return res.json({success: false, msg: 'Username already exists.'});
}
res.json({success: true, msg: 'Successful created new user.'});
});
}
});
Then this is my user model aka user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = module.exports = mongoose.model('customers', new Schema({
name : {
type: String
},
email : {
type : String
},
password : {
type : String
}
}));
// Add user
module.exports.addUser = function(user, callback){
User.create(user, callback);
}
Anything wrong with my logic? I'm stuck for hours for this. I can see something when I do console.log(User) but when I try to create an instance it says it's not defined.

There's nothing that I can see that's wrong with your logic, but the exports in your user model seem wrong.
First you set your entire module.exports object to the mongoose model:
var User = module.exports = mongoose.model('customers', UserSchema);
which would be imported like this:
var User = require('../models/user');
Which is just as you did.
But then you write over that, by exporting the addUser function/key. The User model is no longer exported at all. So in fact all you can really do with your module as it stands is:
var userStuff = require('../models/user');
userStuff.create(...);
As for how to fix it, you have many choices. The minimal change is probably something like this:
var User = module.exports.User = mongoose.model('customers', UserSchema);
And then import it like this:
var User = require('../models/user').User;

Related

How to populate using mongoose? I have a problem

I'm making a simple example of CRUD for a larger and open source project. Right now I want to populate with user data, I have already looked at the documentation and some forums and I am not able to solve the problem that is causing here.
The message in terminal "Populated User undefined"
Could anyone help?
userModel
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
name: {
type: String
},
});
userController
var mongoose = require('mongoose'),
User = mongoose.model('Users');
exports.create_a_user = function(req, res) {
var new_user = new User(req.body);
new_user.save(function(err, user) {
if (err)
res.send(err);
res.json(user);
});
};
msgModel
module.exports = mongoose.model('Users', userSchema);
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var msgSchema = new Schema({
title: {
type: String
},
body: {
type: String
},
created_date: {
type: Date,
default: Date.now
},
user : {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
});
module.exports = mongoose.model('Messages', msgSchema);
msgController
var mongoose = require('mongoose'),
Message = mongoose.model('Messages');
exports.list_all_messages = function (req, res) {
Message.find({})
.populate('user')
.exec((err, msg) => {
if (err)
res.send(err);
res.json(msg);
});
};
module.exports = mongoose.model('Users', userSchema);
maybe in msgSchema you have to reference 'users' instead of 'user'
So, I found the error in the code, in the user's schema there was a lack of reference to the export of the name that was placed in the user's model.
user : {
type: mongoose.Schema.Types.ObjectId,
ref: 'Users'
},
So,...
module.exports = mongoose.model('Users', userSchema);

TypeError: User is not a constructor

I am trying to save a user to mongodb database using post request as follow, but I got the error TypeError: User is not a function. It's a pretty simple set up of the code but i can't figure out anything wrong with it.
I am using:
mongoose 4.8.6
express 4.15.2
node 6.6
// models/user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
email: {
type: String,
unique: true,
lowercase: true
},
password: String
});
// server.js
var User = require('./models/user');
app.post('/create-user', function(req, res, next) {
var user = new User(); // TypeError: User is not a constructor
user.email = req.body.email;
user.password = req.body.password;
user.save(function(err) {
if (err) return next(err);
res.json('Successfully register a new user');
});
});
You need to create model from your UserSchema and then export it, then you can create new User objects.
// models/user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
email: {
type: String,
unique: true,
lowercase: true
},
password: String
});
module.exports = mongoose.model('User', UserSchema)
You got that error because you exported the modules wrongly,
In my case in the models/user I had written module.export leaving out the s at the end
When you run the code it then gives you that error
I would advice checking on your module.exports = mongoose.model('User', UserSchema) spellings
// models/user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
email: {
type: String,
unique: true,
lowercase: true
},
password: String
});
var User = mongoose.model('User', UserSchema)
module.exports = { User } <-- capital 'U'
Changing the lowercase user variable into uppercase (like below) strangely worked:
const User = mongoose.model('users');
I really thought this was just a best practice but eventually, seems to be mandatory.
Change this var user = new User(); for this var User = new User();
I was also facing the same error but this worked for me.
I did change my export file
var User = mongoose.model('User',userSchema);
module.exports = {User};
To
module.exports = mongoose.model('User', userSchema);

mongoose, node, cannot use the method defined in user.model.js

I am using node and mongoose to build an app. And when testing, there exists a strange problem. Here is my auth.index.js(for user login).
auth.index.js:
var express = require('express');
var mongoose = require('mongoose');
var passport = require('passport');
var config = require('../config/environment');
var User = require('../api/user/user.model');
var jwt = require('jsonwebtoken');
var auth = require('./auth.service');
var router = express.Router();
router.post('/login', function (req, res, next){
User.find({email: req.body.email}, function (err, user){
if (err) {
return next(err);
} else if (!user) {
return res.json({message: 'Invalid email.'});
} else {
if(!user.authenticate(req.body.password)){
return res.json({message: 'Invalid password.'});
};
var token = auth.signToken(user._id, user.username, user.role);
return res.json({token: token});
};
});
});
Here is the user.model.js:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
username: String,
password: String,
email: {type: String, lowercase: true},
role: {type: String, default: 'user'},
provider: String,
date: String
});
UserSchema.methods = {
//check password
authenticate: function(plainText) {
return plainText === this.password;
}
};
However, in the command window, it returns that
user.authenticat is not a function.
I wanna know why, and does it mean that I cannot use the method directly or I need to invoke the method through passport ? Thanks.
I think you have misplaced your methods. It should be like this.
UserSchema.methods.authenticate: function(plainText) {
return plainText === this.password;
}
See the following link for the complete example. https://scotch.io/tutorials/using-mongoosejs-in-node-js-and-mongodb-applications

Mongoose Populate returning undefined when requiring schema from another File

I'm making a node application. Users can have favorite Listings of rooms ( just like wish list). I'm trying to add listings ids to user favorite listings but that always gives undefined. if i do "console.log(users.favoriteListings);" the output comes to be undefined. Any help please.
listingModel.js
var mongoose = require("mongoose");
var Schema = mongoose.Schema;//creating schema
var ListingSchema = new Schema({
location: {//ROOM LOCATION
type: [Number], // [<longitude>, <latitude>]
index: '2d' // create the geospatial index
},
}
);
var Listing = mongoose.model('Listing', ListingSchema);
module.exports = Listing;
userModel.js
var mongoose = require("mongoose");
var Schema = mongoose.Schema;//creating schema
var Listing=require('../listing/listingModel');
var UserSchema = new Schema({
favoriteListings : [{ type: Schema.Types.ObjectId, ref: 'Listing' }],
}
);
var User = mongoose.model('User', UserSchema);
module.exports = User;
userController.js
addFavListing:function(req,res){
//READ TOKEN AND FIND USER ID, IF USER HAS REACHED THIS POINT, THIS MEANS THAT TOKEN ALREADY
//HAS BEEN VERIFIED
var token = req.body.token || req.query.token || req.headers['x-access-token'];
var decoded=jwt.verify(token, app.get('superSecret'));
var id=decoded._doc._id;console.log(id);
User.find({_id:id}).populate('favoriteListings').exec(function(err,users) {
if (err){ return handleError(err);}
console.log(users.favoriteListings);
});
You got an array of users from mongoose.
This array has no favoriteListings property.
But each user in the array must have his favoriteListings.
In your userController, try to replace the console.log by this one:
console.log(users.forEach(function(user) {
console.log(user.favoriteListings);
}));

Mongoose TypeError: object is not a function when instantiating object of a schema type

the issue i'm having is that mongoose isn't letting me instantiate an object of a schema type, inside a 'pre' method, of a different schema.
I've got 2 schemas - 'User' and 'Tickit'.
User.js
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var Schema = mongoose.Schema;
var Tickit = require('../models/Tickit');
var userSchema = new Schema({
email : String,
password : String,
tickits : [Tickit.tickitSchema]
});
userSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
userSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.password);
};
module.exports = mongoose.model('User', userSchema);
and Tickit.js
var mongoose = require('mongoose');
var User = require('../models/User');
var Schema = mongoose.Schema;
var tickitSchema = new Schema({
title: String,
description: String,
author : { type: Schema.Types.ObjectId, ref: 'User' },
comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}]
});
tickitSchema.pre('save', function(next){
var user = new User();
user.tickits.push ({id:this._id});
user.save(function(err){
if(err)
res.send(err)
.populate('tickits')
.exec(function(err, blah){
if(err) res.send(err);
})
res.json(blah);
})
next();
})
module.exports = mongoose.model('Tickit', tickitSchema);
What i'm trying to do with the pre method in Tickit is populate the 'Tickits' array in the User schema with the id of that Tickit every time a Tickit is created.
However in my app when I do create a tickit, the app crashes and I get this error
var user = new User();
^
TypeError: object is not a function
Try to define user inside your function:
tickitSchema.pre('save', function(next){
var User = require('../models/User');
// Code
});

Categories