route/signup.js
var express = require('express');
var router = express.Router();
const User = require('../model/user');
var mongoose = require('mongoose');
function userFind(value){
return User.find({user_id:value}).exec();
};
router.get('/',function (req,res) {
res.render('login/signup');
});
router.post('/',async function (req,res,next){
try{
let userid =req.body.id;
console.log(userid); //abcdefg
const user = await userFind(userid);
console.log(user); // []
}catch(err){
next(err);
}
})
module.exports = router;
model/user.js
const mongoose = require('mongoose')
var Schema = mongoose.Schema;
const userSchema = new Schema(
{ user_id : {type:String,required:true, unique:true},
user_password : {type:String, required:true, select:false},
user_name: {type:String, required:true},
user_email : {type:String,required:true,unique : true},
user_birth : {type:String,require:true},
},{versionKey:false},
{collection: 'user'}
);
module.exports = mongoose.model('user',userSchema);
data inside mongodb.
{
"_id": {
"$oid": "60413c7c48e5e61187cc4eeb"
},
"user_id": "abcdefg",
"user_password": "test111",
"user_name": "세글자",
"user_email": "test#naver.com",
"user_birth": "884455"
}
app.js
var express = require('express');
var mongoose = require('mongoose');
const bodyParser = require('body-parser');
var db = mongoose.connection;
db.on('error', console.error);
db.once('open', function(){
// CONNECTED TO MONGODB SERVER
console.log("Connected to mongod server");
});
mongoose.connect("mongodb+srv://testing1:7894#cluster0.9hxjc.mongodb.net/data?
retryWrites=true&w=majority", { useNewUrlParser: true, useUnifiedTopology:
true });
var app = express();
var test = require('./route/index');
var test2 = require('./route/signup');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.set('views',__dirname+'/views'); // ==
app.set('views',path.join(__dirname, 'views'));
app.set('view engine','ejs');
app.engine('html',require('ejs').renderFile);
app.use('/',test);
app.use('/signup.ejs',test2);
app.listen(3000,function(){
console.log('hello world');
});
Hello, I am studying using mogoose and node.js. I ran mongoose find() but the result was only []. I don't know why this is so, I would appreciate it if you let me know. And if it is findOne(), how should I write it? I tried writing it once, but it turned out to be null.
Through chatting in comments we found the issue. The model is called user:
module.exports = mongoose.model('user',userSchema);
Which mongoose will connect to a collection named users (plural) in MongoDB. That collection was indeed empty. There was only content in a collection named user.
Related
Need help, I am trying to learn nodejs from youtube. I have created below but not getting any response from browser. Can you please check below code and advise what I have missed??
if I removed the courseModel.find ... from course.js and just write resp.send("XYZ") its showing on browser otherwise nothing is showing. please help
seems something is missing in mangodb connection string
--index.js
const connection = require('./model/connection');
const express = require('express');
const app = express();
const handleBars = require('express-handlebars');
const bodyParser = require('body-parser');
const http = require('http');
const path = require('path');
const courseController = require('./controllers/course');
const server = http.createServer(app);
app.use(bodyParser.urlencoded({
extended: true,
}))
app.use("/course", courseController);
server.listen(3900, () => {
console.log("server is in running mode.");
});
--connection.js
const mongoose = require('mongoose');
var conn = mongoose.createConnection("mongodb://localhost:27017/learning", (err) => {
if (!err) {
console.log("Mongo db connected");
} else {
console.log(err);
}
});
const courseModels = require("./course.model");
--course.model.js
const mongoose = require('mongoose');
var CourseSchema = new mongoose.Schema({
courseName: {
type: String,
required: 'Required'
},
courseId: {
type: String,
},
courseDuration: {
type: String,
}
});
module.exports = mongoose.model("Course", CourseSchema);
--course.js
const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
const courseModel = mongoose.model("Course");
router.get("/lists", (req, resp) => {
courseModel.find((err,docs)=>{
if(!err){
resp.send(docs)
}
});
});
module.exports = router;
--logs
issue resolved after updating the connection.js as below
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/learning',
{
useNewUrlParser: true,
// useFindAndModify: false,
useUnifiedTopology: true
}, console.log("mongo db connected")
);
Insted of .
server.listen(3900, () => {
console.log("server is in running mode.");
});
use :
app.listen(3900, () => {
console.log("server is in running mode.");
});
Code never executes to the console.log("in") so findOne is not being run. RoboT3 also doesnt show auth db. Mongo version is the latest 4.0.3.
controllers/authentication.js
const User = require('../models/user');
exports.signup = (req, res, next) => {
console.log(req.body)
const email = req.body.email;
const password = req.body.password;
// check for duplicate users by email
User.findOne({email: email}, (err, existingUser) => {
console.log("in")
if (err) {return next(err)}
// if duplicate found, return error
if (existingUser) {
return res.status(422).send({error: 'Email is in use'});
}
const user = new User({
email: email,
password: password
});
user.save((err) => {
if (err) {return next(err); }
res.json(user);
})
});
// if not, create and save record and return
}
index.js
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const morgan = require ('morgan');
const router = require('./router');
const mongo = require('mongodb');
mongo.connect('mongodb://localhost:27017/auth', { useNewUrlParser: true });
const App = express();
// App setup
App.use(morgan('combined'));
App.use(bodyParser.json());
router(App);
// Server setup
const port = process.env.PORT || 3090;
const server = http.createServer(App);
server.listen(port);
console.log("server running on port " + port);
router.js
const authentication = require('./controllers/authentication');
module.exports = function (app) {
app.post('/signup', authentication.signup);
}
models/user.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema ({
email: {type: String, unique: true, lowercase: true},
password: String
});
const ModelClass = mongoose.model('user', userSchema);
module.exports = ModelClass;
Why not use mongoose in your index.js ?
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/auth', { useNewUrlParser: true });
let db = mongoose.connection;
db.once('open', function callback () {
console.log("connected to db");
});
// controllers/users.js
'use strict';
var mongoose = require('mongoose'),
User = mongoose.model('Users');
exports.list_all_users = function(req, res) {
User.find({}, function(err, users) {
if (err)
res.send(err);
res.json(users);
});
};
// exports.list_all_users = function(req, res){
// res.send("display all users");
// };
exports.create_a_user = function(req, res){
res.send("user_created");
};
exports.delete_a_user = function(req, res){
res.send("user_deleted");
};
./routes/users.js
'use strict';
module.exports = function(app) {
var users = require('../controllers/users');
// users Routes
app.route('/users')
.get(users.list_all_users);
}
model/UserModel.js
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
_id:{
type : Number,
auto : true },
name: {
type : String,
required: 'Kindly enter the name '
},
password: {
type: String
},
email:{
type: String,
required: 'Kindly enter the mailId '
},
role:{
type: String,
required : 'Enter a valid role '
},
invitedBy: {
type: Number,
required : 'Valid number'
}
});
module.exports = mongoose.model('Users', UserSchema);
server.js
var express = require('express'),
app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
User = require('./model/UserModel'), //created model loading here
bodyParser = require('body-parser');
// mongoose instance connection url connection
var dbConfig = require('./db');
mongoose.Promise = global.Promise;
mongoose.connect(dbConfig.config);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var userRoutes = require('./routes/users'); //importing route
userRoutes(app); //register the route
app.listen(port);
console.log('todo list RESTful API server started on: ' + port);
I tried printing 'display as respone' to response and it works, the database connection is successful.
But when I try to get from the db, it prints[] for /users get
I suspect something is wrong with my model
Can anyone point out what went wrong here ?
My collection:
collection : "Users"
{
"_id": 112,
"name": "abcd",
"password": "hash12341234",
"email": "questioner#hotmail.com",
"role": "musician",
"invitedBy": 1
}
In you controllers/user.js, you have tried to created a user model again. Can you try importing as follows,
var mongoose = require('mongoose'),
User = require('../model/UserModel')
In you userModel.js, you need to also place a connection string
var db = mongoose.connect("mongodb://localhost/XXXXX");
var Schema = mongoose.Schema;
You just need to replace a line in controller/user.js
Use:
User = require('../model/UserModel')
instead of:
User = mongoose.model('Users');
Hope this helps.
Actually, the issue is that, the get function is returning the objects in collection created only using the model in Node.
I tried creating the user with the api and tested get users but it works like charm.
I am still puzzled about why it is unable to return the objects from the collection which were created by me manually.
I am trying to post the user data to mongodb but I am getting an error as :
`TypeError: user.save is not a function' - how to fix this?
here is my code :
var
express = require('express'),
app = express(),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
PORT = process.env.PORT || 8080;
//connect to db
mongoose.connect('mongodb://3gwebtrain:admsin#ds147975.mlab.com:47975/family');
app.use( bodyParser.urlencoded({extended : true }));
app.use( bodyParser.json() );
app.get('/', function( req, res ) {
res.json({message:'works'})
});
var Schema = mongoose.Schema;
var User = new Schema({
name:String,
username:{type:String, required:true, index:{unique:true}},
password:{type:String, required:true, select:false}
})
var apiRouter = express.Router();
apiRouter
.get('/users', function( req, res ){
res.send( "yet to get users!");
})
.post('/users', function( req, res ) {
var user = User;
user.name = req.body.name;
user.username = req.body.username;
user.password = req.body.password;
user.save(function(err) {
if( err ) {
console.log( err ); //TypeError: user.save is not a function
}
res.send("user created!");
})
})
app.use('/api', apiRouter);
app.listen( PORT );
console.log( 'app listens at ' + PORT );
first create model from Schema :
var UserModel = mongoose.model('User', User);
then create object out of User model
var user = new UserModel(req.body)
then call
user.save(function(){})
check documentation
http://mongoosejs.com/docs/api.html#model_Model-save
You will need to also define a model, change your schema definition to this:
var UserSchema = new mongoose.Schema({
name:String,
username:{type:String, required:true, index:{unique:true}},
password:{type:String, required:true, select:false}
})
var User = mongoose.model('User', UserSchema);
Then you should be good to go :)
The issue that it doesnt let me use the genre schema
i have 2 schemas user and genre
user schema works fine but the genre schema is undefind
user.js - schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Genre = require('../Models/genre');
// create a schema
var userSchema = new Schema({
name: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
age: String,
gender: String,
genres: [Genre.genreSchema]
});
// the schema is useless so far
// we need to create a model using it
var User = mongoose.model('User', userSchema);
// make this available to our users in our Node applications
module.exports = User;
genre.js - schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a schema
var genreSchema = new Schema({
name: { type: String, required: true, unique: true },
age: String,
gender: String
});
// the schema is useless so far
// we need to create a model using it
var Genre = mongoose.model('Genre', genreSchema);
// make this available to our genres in our Node applications
module.exports = Genre;
genre controller - router --- same as user router controller
var express = require('express');
var bodyParser = require('body-parser');
var Genre = require('../Models/genre');
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router
// middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('Something is happening.');
next(); // make sure we go to the next routes and don't stop here
});
router.route('/genres')
// create a genre
.post(function(req, res) {
console.log(Genre);
**//here is the error when trying to post new genre**
var Genre = new Genre(req.body); // create a new instance of the user model
// save the genre and check for errors
Genre.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Genre created!' });
});
})
// get all the genres
.get(function(req, res) {
Genre.find(function(err, genres) {
if (err)
res.send(err);
res.json(genres);
});
});
module.exports = router;
server.js - the app js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var userRouter = require('./Controllers/user');
var genreRouter = require('./Controllers/genre');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017'); // connect to our datababase
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', userRouter);
app.use('/api', genreRouter);
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('see whats happening on port ' + port);
why the model is undefind only when i post new genre? and for user it works fine?
is it the way to do schema whithin schema? or there is a better way?
i have try to use only the genre model with out the user and it still same error
i hope i am clear enough
thanks for the helpers
You shouldn't be using the same name for the schema and for the new Genre.
try changing it to
var newGenre = new Genre(req.body); // create a new instance of the user model
// save the genre and check for errors
newGre.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Genre created!' });
});