I have two forms (signup form and an other form XYZ) in one Reactjs/Nodejs project.
How to post the two forms data to two different databases table, each one autonome ?
PS: I'm new in Nodejs, Thanks in advance.
My codes so far:
server.js:
const express = require('express')
const mongoose = require('mongoose')
const bodyparser = require('body-parser')
const FormRoute = require('./routes/FormRoute')
//database
mongoose.connect('mongodb://localhost:27017/form', { useNewUrlParser: true, useUnifiedTopology: true })
const db = mongoose.connection
db.on('error', (err) => {
console.log(err)
})
db.once('open', () => {
console.log("Database connection established!")
})
//app
const app = express()
app.use(bodyparser.urlencoded({ extended: true }))
app.use(bodyparser.json())
//cors
const cors = require('cors')
app.use(cors())
//server run
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
})
app.use('/api/form', FormRoute);
FormModel.js: (this is signup form model)
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const formSchema = new Schema({
title: {
type: String
},
fname: {
type: String
},
lname: {
type: String
},
email: {
type: String
},
phoneNumber: {
type: String
},
cv: {
type: String
},
coverLetter: {
type: String
},
score: {
type: Number,
default: 0
}
}, { timestamps: true })
const form = mongoose.model('form', formSchema)
module.exports = form
FormXYZModel.js: (this is XYZ form model)
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const formXYZSchema = new Schema({
name: {
type: String
},
email: {
type: String
},
password: {
type: String
},
dateOfBirth: {
type: Date
},
role: {
type: String,
default: user
}, { timestamps: true })
const formXYZ = mongoose.model('formXYZ', formSchema)
module.exports = formXYZ
Related
To start with I am noob in node.js and MongoDb and working with tutorial with Lama Dev social media as a basic project kindly help
in Postman
error 404 is coming
where in the video it's 200 ok
I have copied main code for 100-1000 times help
This Is my auth.js file
//auth.js
const router = require("express").Router();
const User = require("../models/User");
//register
router.post("/register", async (req, res) =>{
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password,
});
try{
const user = await newUser.save();
res.status(200).json(user);
} catch(err) {
console.log(err);
}
});
module.exports = router;
This Is my User.js file in models folder
//User.js
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
username: {
type: String,
require: true,
min: 3,
max: 20,
unique: true,
},
email: {
type: String,
required: true,
max: 50,
unique: true,
},
password: {
type: String,
required: true,
min: 6,
},
profilePicture: {
type: String,
default: "",
},
coverPicture: {
type: String,
default: "",
},
followers: {
type: Array,
default: [],
},
followings: {
type: Array,
default: [],
},
isAdmin: {
type: Boolean,
default: false,
},
}, {timestamps: true});
module.exports = mongoose.model("User", UserSchema);
This Is my index.js file
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const helmet = require("helmet");
const morgan = require("morgan");
const userRoute = require("./routes/users");
const authRoute = require("./routes/auth");
dotenv.config();
mongoose.connect(process.env.MONGO_URL, ()=> {
console.log("MongoDb Connected");
});
//middleware
app.use(express.json());
app.use(helmet());
app.use(morgan("dev"));
app.use("/api/users", userRoute);
app.use("/api/auth", authRoute);
app.listen(8800, ()=>{
console.log("Backhend server is running");
})
And this is a screenshot of postman
Postman ScreenShot Click here
Your POSTMAN screenshot shows your HTTP verb being GET, but the route your registered is using POST. Try changing the verb in POSTMAN.
i am new to MERN framework
try to use postman to test my get and post request. but keep getting this error SyntaxError: Unexpected token b in JSON at position 3
here is my schema -------------------------
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const UserSchema = new Schema({
firstname: {
type: String,
required: true
},
lastname: {
type: String,
required: true
},
sex: {
type: String,
required: true
},
age: {
type: Number,
required: true
},
password: {
type: String,
required: true
},
admin: {
type: Boolean,
default: true
}
});
module.exports = User = mongoose.model("user", UserSchema);
here is my route---------------------
const express = require("express");
const router = express.Router();
const User = require("../../models/user");
router.get("/", (req, res) => {
User.find()
.sort({ age: -1 })
.then(users => res.json(users));
});
router.post("/", (req, res) => {
const newUser = new User({
firstname: req.body.firstname
});
newUser.save().then(user => res.json(user));
});
module.exports = router;
here is my server------------------
const express = require("express");
const mongoose = require("mongoose");
const users = require("./routes/api/users");
const app = express();
app.use(express.json());
const db = require("./config/keys").mongoURI;
mongoose
.connect(db, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err));
app.use("/api/users", users);
const port = 5000;
app.listen(port, () => console.log(`server started on port ${port}`));
please help!! stuck for whole day
You do not need express.json() for GET routes. So please try moving app.use(express.json()); to route file before POST request.
Also if you are using express version >= 4, please use app.use(bodyParser.json()) from body-parser package.
I created a simple node/express api connected to mongo atlas, i try to send post requests to add new data to the database with rest client extension in vscode but keep on running into the above error not sure where I have messed up in my code
main server file with middleware
const express = require("express");
const app = express();
const coolapi = require("./api/coolapi");
const dotenv = require("dotenv");
const mongoose = require("mongoose");
dotenv.config();
mongoose.connect(process.env.DB_ACCESS, { useUnifiedTopology: true }, () => {
console.log("DB connected");
});
app.use(express.json());
app.use("/api/coolapi", coolapi);
app.listen(3000, () => {
console.log("server is running");
});
File with express Router
const express = require("express");
const router = express.Router();
const coolioObj = require("../models/CoolModel");
router.post("/signup", (request, response) => {
const coolPerson = new coolioObj({
username: request.body.username,
email: request.body.email,
password: request.body.password,
});
coolPerson
.save()
.then((data) => {
response.json(data);
})
.catch((error) => {
response.json(error);
});
});
module.exports = router;
file with mongoose schema
const mongoose = require("mongoose");
const coolioSchema = mongoose.Schema({
username: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("coolioDB", coolioSchema);
request being sent
POST http://localhost:3000/api/coolapi/signup http/1.1
Content-Type: application/json
{
"username":"samthingsoweto",
"email":"sams#amapiano.co",
"password":"KabzaDaSmall",
}
JSON arrays doesn't support a comma after the last item. That is the cause of the error. Delete the last comma in all JSON arrays.
date: {
type: Date,
default: Date.now,
}, <---
{
"username":"peoplefrom",
"email":"peopleperson#email.com",
"password":"peoplepassword123", <---
}
I have copied the code from another application, and that is working fine. but this one is giving me a Typeerror: cannot read property find of undefined when I am making the request to the database using the api.
here is my server.js
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");
const userRoutes = express.Router();
const PORT = 4000;
let { User } = require("./models/User");
app.use(cors());
app.use(bodyParser.json());
mongoose.connect("mongodb://127.0.0.1:27017/school", { useNewUrlParser: true });
const connection = mongoose.connection;
connection.once("open", function() {
console.log("MongoDB database connection established successfully");
});
userRoutes.route("/").get(function(req, res) {
User.find(function(err, users) {
if (err) {
console.log(err);
} else {
res.json(users);
}
});
});
app.use("/users", userRoutes);
app.listen(PORT, function() {
console.log("Server is running on Port: " + PORT);
});
here is my User Model:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
let User = new Schema({
firstName: {
type: String,
required: "First name is required"
},
lastName: {
type: String,
required: "Last name is required"
},
emailAddress: {
type: String,
required: "Email address is required",
match: [
/^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
"A valid email address is required"
]
},
password: {
type: String,
required: "Password is required"
}
});
module.exports = mongoose.model("User", User);
Your problem is the wrong way of importing User Schema , you can fix it like so :
let User = require("./models/User");
now your functions will work fine :)
I've declared a file called commentSchema which has some fields:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const moment = require('moment');
var commentSchema = new Schema ({
comment_text: {type: String, required: true},
user_token: {type: String, required: true},
activity_id: { type: Schema.ObjectId, ref: 'Activity', required: true },
is_hidden: { type: Boolean, "default": false },
created_at: { type: Number, "default": moment().unix() },
updated_at: { type: Number, "default": moment().unix() }
})
module.exports = mongoose.model('Comment', commentSchema);
and this is my router file:
var Router = require('router');
var router = Router();
var express = require('express');
var app = express();
// importing Models
var userSchema = require('./models/userSchema.js');
var activitySchema = require('./models/activitySchema.js');
var commentSchema = require('./models/commentSchema');
// Parsing the informations get from the client
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
router.get('/comments', (req, res) => {
});
router.post('/comment', (req, res) => {
var newComment = {
comment_text: req.body.comment_text,
user_token: req.body.user_token,
activity_id: req.body.activity_id
}
console.log(newComment);
commentSchema.create(newComment, (err) => {
if (err){
console.log(err);
}
else{
console.log('DONE!');
}
})
})
module.exports = router;
I'm trying to send post request using POSTMAN but I get the following error:
Cannot read property 'comment_text' of undefined
From the documentation of router. It says you have to use following:
router.use(bodyParser.json())