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?
Related
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;
I've been trying to sequentially upload my json file to MongoDB using the Bulk API. But everytime I try to do so I receive the following error "TypeError: bulk.insert is not a function"
I've referenced the docs and my syntax looks alright. Do let me know how I can go about fixing the same.
Below is my code snippet.
productRouter.js
const products = require('../models/product');
productRouter.route('/bulkupload')
.get((req,res,next) => {
var productJson = fs.readFileSync('development/mongodb-file-import.json');
productJson = JSON.parse(productJson);
console.log(productJson[1])
var bulk = products.collection.initializeOrderedBulkOp();
for (i=0; i < productJson.length; i+=1) {
bulk.insert(productJson[i])
}
bulk.execute(function (errx) {
if (errx) {
return next(errx);
}
console.log('Success');
});
})
EDIT
app.js
const mongoose = require('mongoose');
const product = require('./models/product');
const warehouse = require('./models/warehouse');
const url = process.env.MONGODB_URL_ATLAS;
const connect = mongoose.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
});
connect.then((db) => {
winston.info('Connected correctly to server');
}, (err) => {winston.error(err); });
product.js
const mongoose = require('mongoose');
const shortId = require('shortid');
const Schema = mongoose.Schema;
const productSchema = new Schema({
productName: {
type: String,
required: true,
required: 'Please choose the product from the list!'
},
productUnit: {
type: String,
required: true
},
productPricePerUnit: {
type: Number,
required: true
},
productSku: {
type: String,
required: true,
uppercase: 1,
index: {
unique: true
},
default: "SNS" + shortId.generate()
}
},{
timestamps: true
});
var products = mongoose.model('products', productSchema);
module.exports = products;
I think you can do it with this code below:
productRouter.route('/bulkupload')
.get(async(req, res, next) => {
var products = fs.readFileSync('development/mongodb-file-import.json');
products = JSON.parse(products);
const jobQuerys = [];
products.forEach(p => {
p.productSku = p.productSku ? p.productSku : "SNS" + shortId.generate();
const product = new Product(p);
jobQuerys.push(product.save());
});
const result = await Promise.all(jobQuerys);
console.log(result);
});
I hope it can help you.
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);
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);
}
});
Server.js
const express = require('express'); const mongoose =
require('mongoose');
const routes = require('./routes');
const server = express();
mongoose.connect("mongodb+srv://izaac:izaac#cluster0-hzrrk.mongodb.net/omnistack8?retryWrites=true&w=majority",
{ useNewUrlParser: true });
server.use(express.json()); server.use(routes);
server.listen(3333);
routes.js
const express = require('express'); const DevController =
require('./controllers/DevController');
const routes = express.Router();
routes.post('/devs', DevController.store);
module.exports = routes;
Dev.js
const { Schema, model } = require('mongoose');
const DevSchema = new Schema({ name: { type: String, required:
true, }, user: { type: String, required: true, }, bio:
String, avatar: { type: String, required: true, }, }, {
timestamps: true, });
module.exports = model('Dev', DevSchema);
DevController.js
const axios = require('axios');
const Dev = require('../models/Dev');
module.exports = {
async store(req, res) {
const { username } = req.body;
const userExists = await Dev.findOne({ user: username });
if (userExists) {
return res.json(userExists);
}
const response = await axios.get(`https://api.github.com/users/${username}`);
const { name, bio, avatar_url: avatar } = response.data;
const dev = await Dev.create({
name,
user: username,
bio,
avatar
});
return res.json(dev);
}
};
enter image description here
The 'name' field is required, but the response to your request has no 'name'.
In your schema design, the key name is required, So you need to log what data will be pass in Dev.create().