MongoDB collection doesn't load on port - node.js

the program doesnt show errors but when i run it on browse all i get is 2 brackets
here is my code
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const CompteModel = require('./models/Compte.js');
mongoose.connect('mongodb://localhost:27017/école');
app.get("/getCompte", (req, res) => {
CompteModel.find({}, (err, result) => {
if (err) {
res.json(err);
} else {
res.json(result);
}
});
});
app.listen(3001, () => {
console.log("Hello");
});
Here is the schema of the collection "Compte".
const mongoose = require("mongoose");
const CompteSchema = new mongoose.Schema({ login: { type: String, required: true, }, password: { type: String, required: true,
},
});
const CompteModel = mongoose.model("Compte",CompteSchema); module.exports = CompteModel;

Related

MERN app handling with MongoServerError and send as response

I have a node application using mongo db and Im trying to send back the MongoServerError if there is an error but i only can console.log it like i did in wsService.js
here are my code:
app.js
const errors = require('./helpers/errorHandler');
const users = require('./controllers/wsController')
app.use(errors.errorHandler)
app.use('/ws', ws)
wsModel.js:
const mongoose = require("mongoose");
const { Schema } = mongoose;
const wsSchema= new Schema({
wsKey1: {
type: String,
required: true,
unique: true,
},
wsKey2: {
type: String,
required: true,
}
});
const WS = mongoose.model("ws", wsSchema);
module.exports = WS;
wsService.js:
const WS = require('../models/wsModel')
const createNewInstance= async (object)=>{
console.log(object)
var newInstance = new WS(object)
newInstance.save( (err, session)=> {
if (err) console.log(err);
console.log(session.wsKey1+ " saved to Open Sessions collection.");
return session
});
return {
"session":newInstance
}
}
module.exports = {
createNewInstance,
};
and my controller.js:
router.post('/createNewInstance', (req, res, next)=>{
wsService.createNewInstance(req.body).then(
(session) =>res.send(session)
).catch(
err => next(err)
)
})

Cannot read property 'findOne' of undefined Express js MongoDB

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?

response does not return mongoose

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');
});

Mongoose model.create() responds empty or do not responde

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);

MongoDB not returning data using NodeJS driver application

I'm using mongoose to connect mongoDB. Its a nodeJS application. Right now I'm concerned to get the data and display it in my application. However, it doesn't show any error, neither it displays any data.
Here's my server file
const express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
mongoose = require('mongoose'),
config = require('./DB');
const employeeRoute = require('./routes/employee.route');
mongoose.Promise = global.Promise;
mongoose.connect(config.DB, { useNewUrlParser: true })
.then(() => { console.log('Database is connected') },
err => { console.log('Can not connect to the database' + err) }
);
const app = express();
app.use(bodyParser.json());
app.use(cors());
app.use('/Employees', employeeRoute);
let port = process.env.PORT || 4000;
const server = app.listen(port, function () {
console.log('Listening on port ' + port);
})
and here's my route file
const express = require('express');
const employeeRoute = express.Router();
let Employees = require('../models/Employee');
employeeRoute.route('/').get(function (req, res) {
let employees = [];
Employees.find({}, function (err, results) {
if (err) {
console.log(err);
}
else {
employees = results;
console.log(employees)
res.json(employees);
}
})
})
module.exports = employeeRoute
and lastly my employee.js file
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Employee = new Schema({
first_name: { type: String },
last_name: { type: String },
title: { type: String },
email: { type: String },
gender: { type: String },
location: { type: String },
phone: { type: Number }
},
{ collation: 'Employees' });
module.exports = mongoose.model('Employees', Employee)
Application runs fine without any error. Before posting it to the forum, I've double checked the db and collection names.
any suggestions
It looks like you might just need to refactor your route a little bit in order to ensure you get the results you want. For example, take a look at my following example:
const express = require('express');
const employeeRoute = express.Router();
let Employees = require('../models/Employee');
employeeRoute.route('/').get(function (req, res) {
// Extract data from the request object here in order to search for employees. For example:
const name = req.body.name;
const surname = req.body.surname;
let employees = [];
// Now perform a find on your specific data:
Employees.find({ first_name: name, last_name: surname }, function(err, results) {
if (err) console.log(err);
else employees = results;
console.log(JSON.stringify(employees));
res.json(employees);
});
// Or you can perform a find on all employees
Employees.find({}, function(err, results) {
if (err) console.log(err);
else employees = results;
console.log(JSON.stringify(employees));
res.json(employees);
});
})
module.exports = employeeRoute
As I mentioned in my comment too, your connection may need to be changed to use the correct term: useNewUrlParser
EDIT
I also noticed that in your Employee Schema, you put collation instead of collection - see below:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Employee = new Schema({
first_name: { type: String },
last_name: { type: String },
title: { type: String },
email: { type: String },
gender: { type: String },
location: { type: String },
phone: { type: Number }
}, { collection: 'employees' });
module.exports = mongoose.model('Employees', Employee)
Try that, does it make any difference?
You are doing it wrong buddy.Here's a sample way of inserting data using mongoose.
employeeRoute.route('/').get(function (req, res) {
Employees.create({your_data}) // ex: {email:req.body.email}
.then((employee)=>{
console.log(employee)
res.json(employee);
}).catch((err)=> {
console.log(err);
res.status(400).send({message: "your message"})
})
})
module.exports = employeeRoute

Resources