Kindly request you to point out where I am going wrong.
When I make a POST Request to the URL: http://localhost:1030/apirequestlogs/add
Record is Created in the Collection. However, Only _id, createDate & updateDate Parameters are there in the record.
app.js
let express = require('express');
let path = require('path'); // Required for Routing
let mongoose = require('mongoose');
let cors = require('cors'); // Required for Sending & Receiving Data in Chunk
let bodyParser = require('body-parser'); // Required for Handling URL GET & POST Requests
let dbConfig = require('./db/dbConfig');
let createError = require('http-errors');
mongoose.Promise = global.Promise;
mongoose.connect(dbConfig.db, {
useNewUrlParser: true
}).then(() => {
console.log('Database BE Server Listening on Port 27017');
},
(error) => {
console.log('Error Connecting to msermsdbs Database BE Server. ' + error);
});
const app = express();
app.use(express.static(__dirname));
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.use(cors());
const apirequestlogRoute = require('./models/common/logs/apirequests/apirequestlogRoutes');
app.use('/apirequestlogs', apirequestlogRoute);
const port = process.env.port || 1030;
const server = app.listen(port, () => {
console.log('Database FE Server Listening on Port 1030');
});
app.use((request, response, next) => {
next(createError(404));
});
app.get('/', (request, response) => {
request.send('Invalid Request');
});
app.use(function(error, request, response, next){
if(!error.statusCode) error.statusCode = 500;
response.status(error.statusCode).send(error.message);
});
apirequestlogModel.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
let apirequestlogSchema = new Schema({
nid: Number,
host: String,
url: String,
server: String,
haserror: Boolean,
errorcode: Number,
errordescription: String
},
{
timestamps: true
});
module.exports = mongoose.model("logapirequests", apirequestlogSchema);
apirequestlogRoutes.js
const express = require("express");
const app = express();
const apirequestlogRoute = express.Router();
let apirequestlogModel = require('./apirequestlogModel');
apirequestlogRoute.route('/getall').get((request, response) => {
apirequestlogModel.find((error, data) => {
if(error){
return next(error);
} else {
response.json(data);
};
});
});
apirequestlogRoute.route('/getbyid/:id').get((request, response) => {
apirequestlogModel.findById(request.params.id,(error, data) => {
if(error){
return next(error);
} else {
response.json(data);
};
});
});
apirequestlogRoute.route('/add').post((request, response, next) => {
apirequestlogModel.create(request.body,(error, data) => {
if(error){
return next(error);
} else {
response.json(data);
};
});
});
module.exports = apirequestlogRoute;
Postman POST Request
{
"nid": 123,
"host": "localhost",
"url": "http://localhost:1030",
"server": "localhost",
"haserror": true,
"errorcode": 500,
"errordescription": "Not Found"
}
Postman Output
{
"_id": "6299e1de7106c03a3c6cc06c",
"createdAt": "2022-06-03T10:26:38.494Z",
"updatedAt": "2022-06-03T10:26:38.494Z",
"__v": 0
}
Postman Request & Output Image
Record Created in Database
{ "_id" : ObjectId("6299cd8ee20fd12125ec4c16"), "createdAt" : ISODate("2022-06-03T08:59:58.558Z"), "updatedAt" : ISODate("2022-06-03T08:59:58.558Z"), "__v" : 0 }
The code is correct. In postman I was making post request as text instead of json.
Related
The following code showing TypeError: URLs.find() is not a function for all types requests.
I have Tried to debug the code for an hour but the only conclusion i came is that URLs is not being treated as a model but a simple object and I don't know why is that happening.
Help !! ಥ﹏ಥ
server.js
const dotenv = require("dotenv");
const { default: mongoose } = require("mongoose");
dotenv.config({ path: "./config.env" });
mongoose
.connect(process.env.DB.replace("<PASSWORD>", process.env.DATABASE_PASSWORD))
.then(() => {
console.log(
"DB connected !!",
process.env.DB.replace("<PASSWORD>", process.env.DATABASE_PASSWORD)
);
});
const app = require(".");
app.listen(process.env.PORT, () =>
console.log(`${process.env.PORT} is listening for incoming requests !!`)
);
index.js
const express = require('express')
const morgan = require('morgan')
const shortenerRoutes = require('./routes/shortenerRoutes')
const app = express()
// Middlewares
app.use(morgan('dev'))
app.use(express.json())
app.use((req, res, next) => {
req.body.createdAt = Date.now();
next();
})
// handling Routes and Routes Middlewares
app.use('/api/v1/urls', shortenerRoutes)
app.all('/', (req, res) => {res.status(404).json({
status: 'failed',
data : "ERROR 404 \n Wrong Route"
})})
module.exports = app
Schema
const mongoose = require('mongoose')
const URLsSchema = mongoose.Schema({
URL : {
type : String,
required : true
},
ShortenedURL : {
type : String,
required : true,
},
createdAt : {
type : Date,
required : true
},
keywords : {
type : [String],
}
})
const URLs = mongoose.model('URLs', ShortenerSchema);
module.exports = URLs;
Controller
const URLs = require("../models/shortenerSchema")
exports.getURLs = async (req, res) => {
try {
const URLsData = await URLs.find();
res.status(200).json({
status: "success",
data: URLsData
})
} catch (e) {
console.log(e);
res.status(500).json({
status: "Internal Server Error 500",
data : e
})
}
}
Routes
const { getURLs, postURL, deleteURL, redirectURL } = require("../controllers/shortenerControllers");
const shortenerRoutes = Router();
shortenerRoutes.route('/').get(getURLs).post(postURL);
shortenerRoutes.route('/:id').delete(deleteURL).get(redirectURL)
module.exports = shortenerRoutes
I am using node and express server to run the mongoDb. For connection and schema I am using mongoose. i successfully connect the database and able to post the data by using postman but problem is it does not show the expected query. Mongodb returns me only the id not the query which is name and description
Here is models
const mongoose = require("mongoose");
const { Schema } = mongoose;
const form = new Schema(
{
name: { type: String },
description: { type: String }
},
{
timestamps: true
}
);
const formSubmit = mongoose.model("formSubmit", form);
module.exports = formSubmit;
This is my express server
const express = require("express");
const port = 5000;
const cors = require("cors");
const morgan = require("morgan");
const app = express();
const formSubmit = require("./models");
const mongoose = require("mongoose");
app.use(cors());
app.use(morgan("dev"));
mongoose
.connect(
"url",
{
useUnifiedTopology: true,
useNewUrlParser: true
}
)
.then(() => console.log("DB Connected!"))
.catch(err => {
console.log(err);
});
//get method
app.get("/show", async (req, res) => {
try {
const entrries = await formSubmit.find();
res.json(entrries);
} catch (error) {
console.log(error);
}
});
//post method
app.post("/post", async (req, res, next) => {
try {
const logs = new formSubmit(req.body);
const entry = await logs.save();
res.json(entry);
} catch (error) {
if (error.name === "ValidationError") {
res.status(422);
}
next(error);
}
});
app.listen(port, () => {
console.log(`Server is running port ${port}`);
});
I think the problem is you don't correctly save the documents to the collection, so when you retrieve them only _id fields display.
To be able to read request body, you need to add express.json() middleware to your server.js.
app.use(express.json());
I'm using the MERN stack to build an application for the first time.
In order to log HTTP requests I use "morgan".
I managed to send data to mongodb which seems to be working fine. The problem is that my post request is not coming through. It says "pending" for 4 minutes, then fails.
Here's what I think is the relevant part of my code:
"server.js":
const express = require("express");
const mongoose = require("mongoose");
const morgan = require("morgan");
const path = require("path");
const cors = require("cors");
const app = express();
const PORT = process.env.PORT || 8080;
const routes = require("./routes/api");
const MONGODB_URI =
"...";
mongoose.connect(MONGODB_URI || "mongodb://localhost/app", {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.on("connected", () => {
console.log("Mongoose is connected.");
});
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cors());
app.use(morgan("tiny"));
app.use("/api", routes);
app.listen(PORT, console.log(`Server is starting at ${PORT}`));
Then I've put my routes into another file "api.js":
const express = require("express");
const router = express.Router();
const Lane = require("../models/lanes");
router.get("/", (req, res) => {
Lane.find({})
.then(data => {
res.json(data);
console.log("Get request successful!");
})
.catch(error => {
console.log("Error: ", error);
});
});
router.post("/save", (req, res) => {
const data = req.body;
const newLane = new Lane();
newLane.collection.insertMany(data, err => {
if (err) {
console.log(err);
} else {
console.log("Multiple docs inserted");
}
});
});
module.exports = router;
I'm using axios to send the request. This happens after submitting a form within my application.
reducer function:
const reducer = (state, action) => {
switch (action.type) {
case "add":
axios({
url: "http://localhost:8080/api/save",
method: "POST",
data: [...state, { id: uuid(), title: action.title, tasks: [] }]
})
.then(() => {
console.log("Data has been sent to the server");
})
.catch(() => {
console.log("Internal server error");
});
return [...state, { id: uuid(), title: action.title, tasks: [] }];
The reducer is being used by my context provider component, which looks like this:
export function LanesProvider(props) {
const [lanes, dispatch] = useReducer(reducer, defaultLanes);
return (
<LanesContext.Provider value={lanes}>
<DispatchContext.Provider value={dispatch}>
{props.children}
</DispatchContext.Provider>
</LanesContext.Provider>
);
}
The "add" method inside my reducer is being called when submitting a form inside another component.
Please let me know if I can add anything to my question that would help.
Thank you in advance!
you are not sending any response back to client. Try to modify post method like
router.post("/save", (req, res) => {
const data = req.body;
const newLane = new Lane();
newLane.collection.insertMany(data, err => {
if (err) {
console.log(err);
res.send(err)
} else {
console.log("Multiple docs inserted");
res.send("Multiple docs inserted")
}
});
});
This is indeed a duplicate question however there is no answer.
The problem is that when I save a new record with mongoose through a post request, all that's saved is something like this:
{ "_id" : ObjectId("5d11590975c82f216eaa4712"), "__v" : 0 }
I am following this tutorial so the code should work fine, but regardless here it is:
the mongoose schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Todo = new Schema({
todo_description: {
type: String
},
todo_responsible: {
type: String
},
todo_priority: {
type: String
},
todo_completed: {
type: Boolean
}
});
module.exports = mongoose.model('Todo', Todo);
the code:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const todoRoutes = express.Router();
const PORT = 4000;
let Todo = require('./todo.model');
app.use(cors());
app.use(bodyParser.json());
mongoose.connect('mongodb://127.0.0.1:27017/todos', { useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', function() {
console.log("MongoDB database connection established successfully");
})
todoRoutes.route('/').get(function(req, res) {
Todo.find(function(err, todos) {
if (err) {
console.log(err);
} else {
res.json(todos);
}
});
});
todoRoutes.route('/:id').get(function(req, res) {
let id = req.params.id;
Todo.findById(id, function(err, todo) {
res.json(todo);
});
});
todoRoutes.route('/update/:id').post(function(req, res) {
Todo.findById(req.params.id, function(err, todo) {
if (!todo)
res.status(404).send("data is not found");
else
todo.todo_description = req.body.todo_description;
todo.todo_responsible = req.body.todo_responsible;
todo.todo_priority = req.body.todo_priority;
todo.todo_completed = req.body.todo_completed;
todo.save().then(todo => {
res.json('Todo updated!');
})
.catch(err => {
res.status(400).send("Update not possible");
});
});
});
todoRoutes.route('/add').post(function(req, res) {
let todo = new Todo(req.body);
todo.save()
.then(todo => {
res.status(200).json({'todo': 'todo added successfully'});
})
.catch(err => {
res.status(400).send('adding new todo failed');
});
});
app.use('/todos', todoRoutes);
app.listen(PORT, function() {
console.log("Server is running on Port: " + PORT);
});
the post request:
the get request:
To confirm here's the output in mongodb:
the problem is that the body needs to be Json(application/json) instead of Text
Everything is fine with your code
Just add this line to your todo.model.js
module.exports = mongoose.model('Todo', Todo);
1:
Edit:
I also had this problem and I fixed Content-type: application / json and it worked
make sure you added app.use(express.json()) to your server.js file.
Try using body-parser and use:
app.use(bodyParser.json());
In the app.js file
I'm new at using back-end code.
I'm trying to Insert basic line into MongoDB online DB.
These are my files:
server.js:
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
var db = require('./config/db');
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url, (err, database) => {
if (err) return console.log(err);
db = database.db('note-api');
require('./app/routes')(app, db);
require('./app/routes')(app, database);
app.listen(port, () => {
console.log('We are live on ' + port);
});
})
note_routes.js:
module.exports = function (app, db) {
// const collection =
app.post('/notes', (req, res) => {
const note = { text: req.body.body, title: req.body.title };
db.collection('notes').insert(note, (err, result) => {
if (err) {
res.send({ 'error': err });
} else {
res.send(result.ops[0]);
}
});
});
};
db.js:
module.exports = {
url: "mongodb://laelav:laelav1#ds227594.mlab.com:27594/getremp"
};
Whenever i try using POST and wish to update the online DB - I get an unauthorized error:
unauthorized error
Then I added this line in note_routes.js:
db.grantRolesToUser("laelav", [{ role: "readWrite", db: "getremp" }]);
And got the following "TypeError: db.grantRolesToUser is not a function":
not a function error
Please help!