I created a small project with node+express+mongodb
This is where i call the create user:
const express = require("express");
const User = require("../models/user");
const router = express.Router();
router.post("/register", async (req, res) => {
try {
const user = await User.create(req.body);
return res.send({ user });
} catch (e) {
return res.status(400).send({ error: "Registration failed" });
}
});
module.exports = app => app.use("/auth", router);
and here is the Schema for the user:
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
name: {
type: String,
require: true
},
email: {
type: String,
require: true,
unique: true,
lowercase: true
},
password: {
type: String,
require: true,
select: false
},
createdAt: {
type: Date,
default: Date.now
}
});
const User = mongoose.model("User", UserSchema);
module.exports = User;
But when o make the resquest, it nevers get a response, it waits forever. And when o take out the await from the request, it gets an empty response { "user": {}}
I'm kind lost looking the mongoose documentation (the ideia is to make a simple rest api, i'm used with python, but looking to learn node)
You have to create a new user from User Model as follows:
const express = require("express");
const User = require("../models/user");
const router = express.Router();
router.post("/register", async (req, res) => {
try {
var user = new User(request.body);
var result = await user.create();
return res.send({ result });
} catch (e) {
return res.status(400).send({ error: "Registration failed" });
}
});
module.exports = app => app.use("/auth", router);
Related
I am creating a MERN stack based website, and was able to write GET and POST requests for two out of the three models I have created so far: users and profile. The latest one, tests, is giving an error of Cannot POST /api/tests. Here's the code:
server.js
const connectDB = require('./config/db');
const app = express();
//Connecting DB
connectDB()
app.use(express.json({extended: false}));
app.get('/',(req,res)=>res.send('API Running'));
app.use('/api/users',require('./routes/api/users'));
app.use('/api/auth',require('./routes/api/auth'));
app.use('/api/profile',require('./routes/api/profile'));
app.use('/api/tests', require('./routes/api/tests'));
const PORT = process.env.Port || 5000;
app.listen(PORT, ()=> console.log(`Server started on port on ${PORT}`));
Test.js
const TestSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
domain: {
type: String,
required: true
},
activeStatus: {
type: Boolean,
required: true
},
questions: [
{
question: {
type: String,
required: true
},
option1: {
type: String,
required: true
},
option2: {
type: String,
required: true
},
option3: {
type: String,
required: true
},
option4: {
type: String,
required: true
},
answer: {
type: Number,
required: false
}
}
]
});
module.exports = Test = mongoose.model('test', TestSchema);
tests.js
const router = express.Router();
const { check, validateResult } = require('express-validator/check');
const auth = require('../../middleware/Auth');
const Test = require('../../models/Test');
const User = require('../../models/User');
// #route POST api/tests
// #desc Create or Update a test
// #access Private
router.post('/', [
check('name', 'Name is required').not().isEmpty(),
check('domain', 'Domain is required').not().isEmpty(),
check('status', 'Status is required').not().isEmpty()
],
async (req, res) => {
console.log("entered");
const errors = validationResult(req);
if(!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const {
name,
domain,
status
} = req.body;
//build test object
const testFields = {};
if(name) testFields.name = name;
if(domain) {console.log(123); testFields.domain = domain;}
if(status) testFields.status = status;
testFields.questions = {};
try {
//see if test exists
// let test = await Test.findOne({name});
// if(test){
// return res.status(400).json({ errors: [{msg: "Test already exists"}] });
// }
//create
test = new Test(testFields);
await test.save();
res.json(test);
console.log(testFields);
res.send('Test Created')
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});
// #route GET api/tests
// #desc Get particular test
// #access Private
router.get('/', auth, async (req, res) => {
try {
const test = await Profile.findById(req.test.id);
console.log(test);
if(!test)
return res.status(400).json({ msg: 'Test not found' });
res.json(test);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});
module.exports = router;
Things I've already tried:
Checked and rechecked the URL entered in Postman (http://localhost:5000/api/tests)
Set the URL type in Postman to POST
Made sure the URL was properly registered, and compared with working URLs and files
Even after this, nothing has worked so far. I am fairly new to this, so that might be the cause of my oversight, please do let me know if you can spot where it's going wrong.
I'm trying to add authentication to my ionic application but I get this error that I don't know how to solve it: Cannot read property 'findOne' of undefined
I want to check about the user if he exists in the database or not but for some reason, I get this error when I try the login in postman
please what I'm missing?
here the auth.js
const express = require('express');
const router = express.Router();
const mongoose = require("mongoose");
const _ = require("lodash");
const bcrypt = require('bcrypt');
const joi = require('joi');
const { DRAFBIE } = require('../employees/drafbie');
router.post('/', async (req, res) => {
let user = await DRAFBIE.findOne({ DECAFFE: req.body.DECAFFE})
if (!user) {
return res.send("employee number is wrong");
}
const checkpassword = await bcrypt.compare(req.body.MOT_PASS, user.MOT_PASS);
if (!checkpassword) {
return res.send("Invalid password");
}
res.send("welcome to your account")
});
module.exports = router;
here the drafbie.js
const express = require('express');
const mongoose=require('mongoose');
const router = express.Router();
const bcrypt = require("bcrypt");
const DRAFBIE = mongoose.model("DRAFBIE", mongoose.Schema({
DECAFFE: {
type: Number,
required: true,
minlength: [3, 'the min value is 100'],
maxlength: [5, "the max value is 9999"]
},
DELAFFE: {
type: String,
required: true
},
TYPE: {
type: String,
required: true,
maxlength: 1
},
AR_DELAFFE: {
type: String,
required: true
},
VLD: {
type: Number,
required: true,
max:[1,"the value of the VLD must be 0 or 1 "]
},
MOT_PASS:{
type: String,
required: true,
},
DEMAIL: {
type: String,
},
NATURE: {
type: String,
maxlength: 1
}
}))
router.get("/", async (req, res) => {
const drafbie = await DRAFBIE.find().sort("DECAFFE");
res.send(drafbie);
});
router.post("/", async (req, res) => {
const drafbie = new DRAFBIE({
DECAFFE: req.body.DECAFFE,
DELAFFE: req.body.DELAFFE,
TYPE: req.body.TYPE,
AR_DELAFFE: req.body.AR_DELAFFE,
VLD: req.body.VLD,
MOT_PASS: req.body.MOT_PASS,
DEMAIL: req.body.DEMAIL,
NATURE:req.body.NATURE
})
await drafbie.save();
res.send(drafbie);
})
router.put("/:decaffe&:password", async (req, res) => {
const saltRound = 10;
const drafbie = await DRAFBIE.findOneAndUpdate({ DECAFFE: req.params.decaffe },
{
$set: {
MOT_PASS: await bcrypt.hash(req.params.password,saltRound)
}
},{new:true}
)
await drafbie.save();
res.send(drafbie)
})
async function updateallpassword() {
const saltRound = 10;
const drafbie = await DRAFBIE.updateMany({ MOT_PASS: "123456789" },
{
$set: {
MOT_PASS: await bcrypt.hash("123456789", saltRound)
}
} ,{new:true});
console.log(drafbie + " the update is done successfully");
}
//updateallpassword();
module.exports = router;
exports.DRAFBIE = DRAFBIE;
here the new error when I change :
module.exports = router; exports.DRAFBIE = DRAFBIE;
module.exports.DRAFBIE = DRAFBIE; module.exports.router = router;
You're exporting the model in the wrong way.Try to modify the last lines of your drafbie.js from :
module.exports = router;
exports.DRAFBIE = DRAFBIE;
to :
module.exports.DRAFBIE = DRAFBIE;
module.exports.router = router; // I modified it to export the router object too, it will impact the code where you import the router.
This will allow you to import the DRAFBIE model in the auth.js like you did : const { DRAFBIE } = require('../employees/drafbie');
How do you use the routes defined in your drafbie.js file?
It does not return anything back (hang state) and i see in console
{ _id: 5f05d1527de7984a2c998385, name: 'alexa', age: 12 }. I tried both method promise and callback but still same. Can you guess what could be the issue?
const express = require('express');
const app = express();
const mongoose = require('mongoose');
app.use(express.json());
const TestModel = mongoose.model(
'test',
new mongoose.Schema({
name: {
type: String,
required: true,
},
age: {
type: Number,
required: true,
},
}),
);
app.post('/test', async (req, res, next) => {
const testUser = req.body;
const Test = new TestModel(testUser);
console.log(Test);
/* Test.save(function (err, doc) {
if (err) {
return res.json({ message: 'something went wrong' });
}
res.json(testUser);
}); */
await Test.save();
res.json(testUser);
});
app.listen(4000, () => {
console.log('playground is up');
});
so hello everyone i'm devolpping my authentication backend i set up my routers my models middlewares and everything then i tried to use postman to see if the registation work or not and each time i click on send request nothing happen i don't know what should i do exactly so please can anyone help with this
database/db.js // connection to database
const mongoose = require('mongoose')
require('dotenv').config();
const base = process.env.MONGO_DATA;
try {
mongoose.connect( base,
{useNewUrlParser: true, useCreateIndex: true}, () =>
console.log("database connected"));
}catch (error) {
console.log("could not connect");
}
models/user.model.js
const mongoose = require('mongoose')
const validator = require('validator')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const userSchema = mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
unique: true,
lowercase: true,
validate: value => {
if (!validator.isEmail(value)) {
throw new Error({error: 'Invalid Email address'})
}
}
},
password: {
type: String,
required: true,
minLength: 7
},
tokens: [{
token: {
type: String,
required: true
}
}]
})
userSchema.pre('save', async function (next) {
// Hash the password before saving the user model
const user = this
if (user.isModified('password')) {
user.password = await bcrypt.hash(user.password, 8)
}
next()
})
userSchema.methods.generateAuthToken = async function() {
// Generate an auth token for the user
const user = this
const token = jwt.sign({_id: user._id}, process.env.JWT_KEY)
user.tokens = user.tokens.concat({token})
await user.save()
return token
}
userSchema.statics.findByCredentials = async (email, password) => {
// Search for a user by email and password.
const user = await User.findOne({ email} )
if (!user) {
throw new Error({ error: 'Invalid login credentials' })
}
const isPasswordMatch = await bcrypt.compare(password, user.password)
if (!isPasswordMatch) {
throw new Error({ error: 'Invalid login credentials' })
}
return user
}
const User = mongoose.model('User', userSchema)
module.exports = User
controllers/user.js
const express = require('express')
const User = require('../models/user.model')
const router = express.Router()
router.post('/users', async (req, res) => {
// Create a new user
try {
const user = new User(req.body)
await user.save()
const token = await user.generateAuthToken()
res.status(201).send({ user, token })
} catch (error) {
res.status(400).send(error)
}
})
router.post('/users/login', async(req, res) => {
//Login a registered user
try {
const { email, password } = req.body
const user = await User.findByCredentials(email, password)
if (!user) {
return res.status(401).send({error: 'Login failed! Check authentication credentials'})
}
const token = await user.generateAuthToken()
res.send({ user, token })
} catch (error) {
res.status(400).send(error)
}
})
module.exports = router
index.js
require('dotenv').config()
const express = require('express')
const userRouter = require('./src/routers/user')
const port = process.env.PORT
require('./src/database/db')
const app = express()
app.use(express.json())
app.use(userRouter)
app.listen(port, () => {
console.log(`Server running on port ${port}`)
})
so each time i try to see if i'm signed up or not postman didn't give any response he keep saying <> and no result can someone help me please ?
Have you created " data " and " db " folder in your ' C ' drive?
Here are the steps:
Create a folder on your machine with name mongodb
Create a folder with name data in the mongodb folder
Create one more folder with name db in the data folder
For more, refer here
I'm learning the MERN stack and encountered an issue on the edit route of my child router.
I have the below model schemas in songs.js and students.js files:
const mongoose = require('mongoose');
const studentSchema = mongoose.Schema({
name: { type: String, required: true },
instrument: String,
songs: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Song'
}]
});
const Student = mongoose.model('Student', studentSchema);
module.exports = Student;
const mongoose = require('mongoose');
const songSchema = mongoose.Schema({
name: { type: String, required: true },
img: String
})
const Song = mongoose.model('Song', songSchema);
module.exports = Song
And I have songs.js and students.js files for my routers, with mergeParams set to true for my songs router const songs = express.Router({ mergeParams: true });. I'm attaching it to the students router like this:
students.use('/:id/songs', songs);
e.g., my url parameters become students/student1/songs/song1
All of my other routes are working, but on the update route of my songs router I'm getting an error "TypeError: Student.findById is not a function" when I redirect back to the song's index view. My edit and update routes
are below:
songs.get('/:songId/edit', async (req, res) => {
try {
const findSong = Song.findById(req.params.songId);
const findStudent = Student.findById = (req.params.id);
const [foundSong, foundStudent] = await Promise.all([findSong, findStudent]);
res.render('songs/edit', {
student: foundStudent,
song: foundSong
})
} catch (err) {
console.log(err);
}
});
songs.put('/:songId', async (req, res) => {
try {
const updateSong = await Song.findByIdAndUpdate(req.params.songId, req.body, { new: true });
res.redirect('/students/' + req.params.id + '/songs');
} catch (err) {
console.log(err);
}
});
I'm not sure what's causing the error here, my delete route is set up similarly and is working. Would appreciate any suggestions.
In your rote (req.params.id) is not defining.
songs.get('/:songId/edit', async (req, res) => {
try {
const findSong = Song.findById(req.params.songId);
**const findStudent = Student.findById = (req.params.id);**
const [foundSong, foundStudent] = await Promise.all([findSong, findStudent]);
res.render('songs/edit', {
student: foundStudent,
song: foundSong
})
} catch (err) {
console.log(err);
}
});