I'm using Passport Local Mongoose to create a user on my database. My goal is to allow users with the same username to register into my app. On my research, i found that if i pass an object as option on my Schema.plugin with 'usernameUnique: false', i would allowed users to register with the same username. The only problem is when a try it to make a register, i get an "UserExistsError" on my console.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const passportLocalMongoose = require('passport-local-mongoose');
const UserSchema = new Schema({
email: {
type: String,
required: true,
},
username: {
type: String,
required: true,
unique: false
},
});
const options = {
usernameUnique: false,
}
UserSchema.plugin(passportLocalMongoose, options);
const User = mongoose.model('User', UserSchema);
module.exports = User;
Related
Mongoose gives validation error even if i give the correct create arguments. Checked, function just works one time & variables are not null.
Note: There are several models imported to file with same architecture of Payment Model.
await payment.create({
userId: user._id,
paymentDetails: session
})
Payment Model:
const mongoose = require('mongoose')
const { Schema } = mongoose
mongoose.connect('<REDACTED>')
const Payments = new Schema({
id: String,
userId: { type: String, required: true },
paymentDetails: {type: Object, required: true},
})
module.exports =
mongoose.models.Payments || mongoose.model('Payments', Payments)
I am building a web application in Node with two different types of user. And both of them will have common as well as different properties.
The problem is I am unable to use the common mongoose schema model in another model.
user.js is the common model with the following schema :
//Requiring Mongoose
const mongoose = require('mongoose');
//Creating a variable to store our Schemas
const Schema = mongoose.Schema;
//Create User Schema and Model
const UserSchema = new Schema({
email: {
type: String,
required: [true, 'Email Field is required'],
unique:true,
match: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/
},
name: {
type: String,
required: [true, 'Name field is required']
},
password: {
type: String,
required: [true, 'Please enter your password']
},
phoneNo: {
type: String,
required: [true, 'Phone No is required']
}
//Create a user model which is going to represent our model in the database
and passing our above-created Schema
const User = mongoose.model('user', UserSchema);
//Exporting Models
module.exports = User;
Now I want to use the same UserSchema in another model file rider.js with another property familyNo
I have tried following way but it failed.
//Requiring Mongoose
const mongoose = require('mongoose');
//Importing user Schema to remove the code redundancy
const userSchema = require('./user');
//Creating a variable to store our Schemas
const Schema = mongoose.Schema;
//Create Driver Schema and Model
const RiderSchema = new Schema({
user: userSchema
familyNo: {
type: String,
required: [true, 'Name field is required']
}
});
//Create a rider model is going to represent our model in the database and passing our above-created Schema
const Rider = mongoose.model('rider', RiderSchema);
//Exporting Models
module.exports = Rider;
the problem is you are not passing the schema , you are passing the user model , move your userschema in different file , and use it as schema in both the models , that will solve the problem
//Create a user model which is going to represent our model in the database and passing our above-created Schema
const User = mongoose.model('user', UserSchema);
//Exporting Models
module.exports = User; // Here is the problem, User is a model not schema
UserSchema.js
const UserSchema = mongoose.Schema([Your Common Schema])
User.js
var userSchema = require('./UserSchema');
module.exports = mongoose.model('User', userSchema);
OtherModel.js
var userSchema = require('./UserSchema');
module.exports = mongoose.model('OtherModel' , {
property : String,
user : userSchema
});
I try to create a dedicated mongoose createConnection. Node.js rapports:
MyModel = conn.model('Profile', profileSchema),
profileSchema is not defined. But where did I go wrong?
//my db.js
const mongoose = require('mongoose');
const conn = mongoose.createConnection = ("mongodb://localhost:27017/myDatabase"),
MyModel = conn.model('Profile', profileSchema),
m = new MyModel;
m.save(); //works;
if (process.env.NODE_ENV === 'production') {
conn = process.env.MONGODB_URI;
}
require('./profiles)
Here the rest of my model page:
// my profile.js
// JavaScript source code
const mongoose = require('mongoose');
const profileSchema = new mongoose.Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
});
var MyModel = mongoose.model('Profile', profileSchema);
What you have to do is
// my profile.js
// JavaScript source code
const mongoose = require('mongoose');
const profileSchema = new mongoose.Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
});
module.exports = mongoose.model('Profile', profileSchema);
and in your app.js file put like this
const profileInfo= require('./../model/profile.js');
There are many issues with your code, First learn how module works in javascript.
You need to export the profileSchema inorder to use inside the app.js, it should be,
const mongoose = require('mongoose');
const profileSchema = new mongoose.Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
});
module.exports = mongoose.model('Profile', profileSchema);
then need to import profileSchema which lies inside profile depend on your file path.
const profileSchema = require('./model/profile.js');
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);
I'm creating a chat application with MongoDB (mongoose) and Nodejs. As you see below I have a schema as mongoose allows but my users in storeSchema needs to be an array of Strings (usernames). Is this the proper way to do it?
"use strict";
var express = require('express');
var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
user: String
});
var messageSchema = new mongoose.Schema({
msg: String
});
var storeSchema = new mongoose.Schema({
users: [userSchema], // needs to be an array of users
channels: {
general: {
messages: [messageSchema]
},
videogames: {
messages: [messageSchema]
},
programming: {
messages: [messageSchema]
},
other: {
messages: [messageSchema]
}
}
});
var User = mongoose.model('User', userSchema);
var Message = mongoose.model('Message', messageSchema);
var Storage = mongoose.model('Storage', storeSchema);
module.exports = {
User: User,
Message: Message,
Storage: Storage
}
If you want users to be an array of username strings, then define it in storeSchema as:
users: [String]