I am new in Nodejs. I am using Node.js first time. I am trying to integrate a Nodejs API with React.js application. I don't know why this error is coming. My files are like below.
index.js
import express from 'express';
import path from 'path';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import auth from "./routes/auth";
const app = express();
app.use(bodyParser.json());
mongoose.connect('mongodb://127.0.0.1:8080/bookworm', { useNewUrlParser: true });
app.use("/api/auth", auth);
app.get('/*',(req,res)=> {
res.sendFile(path.join(__dirname,'index.html'));
});
app.listen(8080, ()=> console.log("Running on localhost:8080"));
auth.js
import express from 'express';
import User from '../models/User';
const router = express.Router();
router.post("/", (req,res) => {
const { credentials } = req.body;
User.findOne({ email: credentials.email }).then(user => {
if (user) {
} else {
res.status(400).json({errors: { global: "Invalid creadentials"}})
}
});
});
export default router;
User.js
import mongoose from 'mongoose';
const schema = new mongoose.Schema(
{
email: { type: String, required: true, lowercase: true, index: true },
passwordHash: { type: String, required: true }
},
{ timestamps: true }
);
export default mongoose.model('User', schema);
I am getting error like below
What is the solution ?
Try this:
User.findOne({ email: credentials.email })
.then(user => {
if(!user){
res.status(400).send({errors: { global: "Invalid creadentials"}});
} else {
res.status(200).send({user});
}
})
.catch(errors => {
res.status(400).send({errors: { global: errors.message }});
})
According to the error messages, I just added the catch() method to handle the promise rejection.
Related
I have Error: Package subpath './types' is not defined by "exports" connected with sequelize package.
(Error: Package subpath './types' is not defined by "exports" in D:\Projects\pets\realtime-chat\backend\node_modules\sequelize\package.json).
Tried to solve the problem updating all npm and node versions to the latest ones, but it was unsuccessful. I've setted up express server with socket.io for my app and created User model with sequelize using typescript.
When I try to create new User with User.create({\attributes}) it throws the Error mentioned above.
server.ts
import express from "express"
import { createServer } from "http"
import { Server } from "socket.io";
import apiRouter from "./routes/api.route";
import { seq } from "./models/db"
const app = express();
app.use("/api", apiRouter);
const httpServer = createServer(app);
const io = new Server(httpServer);
io.on("connection", (socket) => {
console.log(socket.id);
});
httpServer.listen(process.env.PORT || 5000, () => {
console.log(seq.config);
seq.authenticate();
console.log("Server is started")
});
User.model.ts
import { DataTypes, Model, Optional } from "sequelize/types";
import { seq } from "./db";
interface UserAttributes {
username: string,
password: string,
email: string
}
type UserCreationAttributes = Optional<UserAttributes, "email">;
class User extends Model<UserAttributes, UserCreationAttributes> {
declare username: string;
declare password: string;
declare email: string
}
User.init({
username: {
type: DataTypes.STRING,
},
password: {
type: DataTypes.STRING
},
email: {
type: DataTypes.STRING
}
},
{
sequelize: seq,
tableName: "users"
});
export default User;
my api.route.ts
import express from "express"
import User from "../models/User";
const router = express.Router();
router.get("/users", async () => {
await User.create({
password: "name",
username: "name"
})
});
export default router;
Just import all these types directly from sequelize:
import { DataTypes, Model, Optional } from "sequelize";
Newbie in Node js, I am using Node JS to build APIs and using class. There are 2 routes till now, one is to fetch all users which is working fine, another is to insert new user which is not working. It is returning {} with status 500.
Here are the files.
index.js
import server from "./config/server.js";
import './config/database.js';
const PORT = process.env.PORT || 5000;
server.listen(PORT, () => {
console.log(`app running on port ${PORT}`);
});
config/database.js
import mongoose from "mongoose";
class Connection {
constructor() {
const url =
process.env.MONGODB_URI || `mongodb://localhost:27017/dev-muscles`;
console.log("Establish new connection with url", url);
mongoose.Promise = global.Promise;
// mongoose.set("useNewUrlParser", true);
// mongoose.set("useFindAndModify", false);
// mongoose.set("useCreateIndex", true);
// mongoose.set("useUnifiedTopology", true);
mongoose.connect(url);
}
}
export default new Connection();
config/server.js
import express from "express";
import UserController from "../src/models/controllers/UserController.js";
const server = express();
server.use(express.json());
server.get(`/users`, UserController.getAll);
server.post(`/users/create`, UserController.create);
export default server;
src/models/User.js
import mongoose from "mongoose";
const { Schema } = mongoose;
import validator from "validator";
class User {
initSchema() {
const schema = new Schema({
first_name: {
type: String,
required: true,
trim: true
},
last_name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
trim: true,
lowercase: true,
// validate(value) {
// if( !validator.isEmail(value) ) {
// throw new Error('Email is invalid')
// }
// }
},
phone: {
type: Number,
required: true,
trim: true
},
password: {
type: String,
required: true
}
});
// schema.plugin(validator);
mongoose.model("users", schema);
}
getInstance() {
this.initSchema();
return mongoose.model("users");
}
}
export default User;
src/controllers/UserController.js
import Controller from "./Controller.js";
import User from ".././models/User.js";
const userModelInstance = new User().getInstance();
class UserController extends Controller {
constructor(model) {
super(model);
}
}
export default new UserController(userModelInstance);
src/controllers/Controller.js
class Controller {
constructor(model) {
this.model = model;
this.getAll = this.getAll.bind(this);
this.create = this.create.bind(this);
}
async getAll(req, res) { // works fine
return res.status(200).send(await this.model.find({}));
}
async create(req, res) { // this is returning {} with status code 500
try {
// return res.send(req.body);
return res.status(201).send(await new this.model.save(req.body));
} catch (error) {
res.status(500).send(error);
}
}
}
export default Controller;
Refactor the create method like so.
const ItemToSave = new this.model(req.body);
const savedItem = await ItemToSave.save();
return res.status(201).send(savedItem);
I created a user signin route from my nodejs backend server and I wanted to test the api but it's returning me with an error, though it's the error I put incase the code is not working as expected. But I cross check the code over and over again, and I can't seem to point where is wrong from the code. Please help by looking at the code may be am doing something wrong, that's why.
**userRouter path**
userRouter.post('/signin', expressAsyncHandler(async (req, res) => {
const user = await User.findOne({ email: req.body.email });
if(user) {
if(bcrypt.compareSync(req.body.password, user.password)) {
res.send({
_id: user._id,
name: user.name,
email: user.email,
isAdmin: user.isAdmin,
token: generateToken(user),
});
return;
}
}
res.status(401).send({ message: 'Invalid email or password verification' });
}))
export default userRouter;
**User model path**
import mongoose from 'mongoose';
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
isAdmin: { type: Boolean, default: false, required: true },
},
{
timestamps: true
}
);
const User = mongoose.model("User", userSchema);
export default User;
**server.js path...**
import express from 'express';
import mongoose from 'mongoose';
import dotenv from 'dotenv';
import productRouter from './routers/productRouter.js';
import userRouter from './routers/userRouter.js';
dotenv.config()
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
mongoose.connect(process.env.MONGODB_URL || 'mongodb://localhost/e-commerce', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
app.use('/api/users', userRouter);
app.use('/api/products', productRouter);
app.get('/', (req, res) => {
res.send('Node server is Serve here');
});
const port = process.env.PORT || 5000;
app.use((err, req, res, next) => {
res.status(500).send({ message: err.message });
});
app.listen(5000, () => {
console.log(`serve at http://localhost/${port}`)
});
**utils.js for generating jsonwebtoken**
export const generateToken= (user) => {
return jwt.signin({
_id: user._id,
name: user.name,
email: user.email,
isAdmin: user.isAdmin,
}, process.env.JWT_SECRET,
{
expiresIn: '30d',
}
);
}
In Express, res.send() is used for string and buffer objects. To send json data you need to use something else:
Instead of res.send(jsondata) use res.json(jsondata)
doc: https://www.geeksforgeeks.org/express-js-res-json-function/
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 am having an issue whereas any data that exists in my MongoDB instance is being removed when I restart my Node/Koa.app. This application uses Mongoose to connect to the local Mongo instance.
Here is my code:
app.js (I have code in there to output connection to the logger)
import Koa from 'koa';
import path from 'path';
import bodyParser from 'koa-bodyparser';
import serve from 'koa-static';
import mongoose from 'mongoose';
import Config from '../Config.js';
global.appRoot = path.resolve(__dirname);
const app = new Koa();
mongoose.connect(Config.mongo.url);
mongoose.connection.on('connected', (response) => {
console.log('Connected to mongo server.');
//trying to get collection names
let names = mongoose.connection.db.listCollections().toArray(function(err, names) {
if (err) {
console.log(err);
}
else {
names.forEach(function(e,i,a) {
mongoose.connection.db.dropCollection(e.name);
console.log("--->>", e.name);
});
}
});
});
mongoose.connection.on('error', (err) => {
console.log(err);
});
The MongoDB config url being referenced in the above module is:
mongo: {
url: 'mongodb://localhost:27017/degould_login'
}
and my Mongoose model:
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
let UserSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
lowercase: true
},
password: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
groupForUsers: [{ type: Schema.Types.ObjectId, ref: 'userGroups' }]
});
export default mongoose.model('users', UserSchema, 'users');
And one of the functions that inserts Data
async register(ctx) {
return new Promise((resolve, reject) => {
const error = this.checkRequiredVariablesEmpty(ctx, [ 'password', 'email' ]);
if(error.length) {
reject(new this.ApiResponse({
success: false,
extras: {
msg: this.ApiMessages.REQUIRED_REGISTRAION_DETAILS_NOT_SET,
missingFields: error
}}
));
}
this.userModel.findOne({ email: ctx.request.body.email }, (err, user) => {
if(err) {
reject(new this.ApiResponse({ success: false, extras: { msg: this.ApiMessages.DB_ERROR }}));
}
if(!user) {
let newUser = new this.userModel();
newUser.email = ctx.request.body.email;
newUser.username = ctx.request.body.username;
newUser.password = ctx.request.body.password;
newUser.save()
.then((err, insertedRecord) => {
When I start the app and populate data into the MongoDB using the register function I can see the data saves into the MongoDB instance correctly.
However, when restarting the application all of these records get removed Is there anything that is causing this in my code? It's impossible for me to have to keep inputting data on every app restart during development.
Your issue is with this line:
mongoose.connection.db.dropCollection(e.name);
...where your collections are being dropped on mongoose 'connected' event.