I am trying to make a post request that saves find data in MongoDB or create one if it does not exist then I got the error like this
MongooseError: Operation `urls.find()` buffering timed out after 10000ms
my main.js
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const app = express();
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
// Basic Configuration
const port = process.env.PORT || 3000;
app.use(cors());
app.use("/public", express.static(`${process.cwd()}/public`));
app.get("/", function (req, res) {
res.sendFile(process.cwd() + "/views/index.html");
});
// Your first API endpoint
app.get("/api/hello", function (req, res) {
res.json({ greeting: "hello API" });
});
app.listen(port, function () {
console.log(`Listening on port ${port}`);
});
mongoose.connect(
process.env.MONGODB_CONNECT,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
},
() => {
console.log("Connected to mongoDB");
}
);
let urlSchema = new mongoose.Schema({
original: { type: String, required: true },
short: Number,
});
let Url = mongoose.model("Url", urlSchema);
let responseObject = {};
app.post(
"/api/shorturl/new",
bodyParser.urlencoded({ extended: false }),
(request, response) => {
let inputUrl = request.body["url"];
responseObject["original_url"] = inputUrl;
let inputShort = 1;
Url.findOne({})
.sort({ short: "desc" })
.exec((error, result) => {
// THE ERROR APPEARS
console.log(error);
if (!error && result != undefined) {
inputShort = result.short + 1;
}
if (!error) {
Url.findOneAndUpdate(
{ original: inputUrl },
{ original: inputUrl, short: inputShort },
{ new: true, upsert: true },
(error, savedUrl) => {
if (!error) {
responseObject["short_url"] = savedUrl.short;
response.json(responseObject);
}
}
);
}
});
}
);
my dependencies
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"mongoose": "^5.11.10"
I already try some solutions in similar question like:
delete node_module file and reinstalled mongoose
change the version of nodejs in MongoDB cluster to
2.2.12 or later
change my IP to google public DNS 8888 8844
any help would be much appreciated
I did try to set up a new environment and using the same MongoDB database, it turns out my database get problem may be the connection,
I tried to create a new project and setup access from everywhere and chose the server near to my place, it works fine now.
The problem
As stated in this answer the problem is very likely to be that YOU DO NOT HAVE your localhost database running.
How to fix
Start both mongod and mongo processes.
Related
When ever I run my server locally it works perfectly
But once I upload it to vercel I get errors like polling-xhr.js:202 GET https://giphy-chat-server.vercel.app/socket.io/?EIO=4&transport=polling&t=NQ03j3c&sid=H_PHDh9-4UKRVGTVAAAC 400
And WebSocket connection to 'wss://giphy-chat-server.vercel.app/socket.io/?EIO=4&transport=websocket&sid=k-Sex1ZKmrQQFoSKAAAA' failed: Error during WebSocket handshake: Unexpected response code: 400
I have tried so many solutions but none is working... I can't just figure out the problem. I would be glad if Its answered. Thank you
const express = require("express");
const app = express();
const http = require("http");
const path = require("path");
var server = http.createServer(app);
const io = require("socket.io")(server, {
cors: {
origin: "*",
credentials: true,
methods: ["GET", "POST"],
},
});
const { MONGODB_URI } = require("./config");
const port = process.env.PORT || 8000;
const Message = require("./message_model");
const mongoose = require("mongoose");
mongoose
.connect(MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
.then((result) => {
server.listen(port, () => {
console.log(`Listening on port ${port}...`);
});
})
.catch((err) => {
console.log(err);
});
app.use(express.static(path.join(__dirname, "..", "client", "build")));
const users = [];
io.on("connection", (socket) => {
users.push({ id: socket.id });
io.emit("users", { users: users });
Message.find()
.sort({ createdAt: -1 })
.limit(10)
.exec((err, messages) => {
if (err) return console.error(err);
socket.emit("init", messages);
});
socket.on("message", (msg) => {
const message = new Message({
content: msg.content,
name: msg.name,
});
message.save((err) => {
if (err) return console.error(err);
});
socket.broadcast.emit("push", msg);
});
socket.on("disconnect", (reason) => {
let index = -1;
for (let i = 0; i < users.length; i++) {
const user = users[i];
if (user.id === socket.id) {
index = i;
}
}
if (index !== -1) {
users.splice(index, 1);
}
io.emit("users", { users: users });
});
});
app.get("/", (req, res) => {
res.send("Giphy Chat Server is running successfully");
});
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
next();
});
I think this will be due to Vercel's serverless functions having a maximum execution timeout, so they can't maintain a websocket connection. In order to use Websockets with Vercel you'll need to use a third party service to handle your websocket connections for you. Something like Ably or Pusher, or PubNub.
I just wrote up a demo of next + ably if it would be helpful - https://github.com/ably-labs/NextJS-chat-app
I am trying to send data through Postman to a REST API made of Node.js and Mongoose
I am getting the following response :
but this does not persist or save to Mongo DB :
I added the following :
mongoose.set("debug", (collectionName, method, query, doc) => {
console.log(`${collectionName}.${method}`, JSON.stringify(query), doc);
});
so I am also getting this at the console (is session supposed to be null)?:
standups.insertOne {"_id":"5f9e54cea6d454065f0a963b","teamMember":"Mark","project":"Trinity Web Application","workYesterday":"Build out the Models","workToday":"Testing the API Endpoint using Postman","impediment":"None","createdOn":"2020-10-31T22:30:03.000Z","__v":0} { session: null }
I have configured with the following files at my server backend :
api/routes/standup.js
const Standup = require('../../models/standup')
module.exports = function (router) {
// GET: the 12 newest stand-up meeting notes
router.get('/standup', function (req, res) {
})
// POST: Get new meeting note document...
router.post('/standup', async function (req, res) {
let note = new Standup(req.body)
await note.save(function (err, note) {
if (err) {
return res.status(400).json(err)
}
res.status(200).json(note)
})
})
}
api/models/standup.js
const mongoose = require('mongoose')
const standupSchema = new mongoose.Schema({
teamMember: { type: String },
project: { type: String },
workYesterday: { type: String },
workToday: { type: String },
impediment: { type: String },
createdOn: { type: Date, default: Date.now }
}, { bufferCommands: false })
module.exports = mongoose.model('Standup', standupSchema)
app.js
const express = require('express')
const app = express()
const api = require('./api')
const morgan = require('morgan')
const bodyParser = require('body-parser')
const cors = require('cors')
const port = process.env.PORT || 8081
app.set('port', port)
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))
app.use(cors())
app.use('/api', api)
app.use(express.static('static'))
app.use(morgan('dev'))
app.use(function (req,res) {
const err = new Error('Not Found')
err.status = 404
res.json(err)
})
const mongoose = require('mongoose')
mongoose.connect('mongodb://127.0.0.1:27017/virtualstandups', {useNewUrlParser: true, bufferCommands: false})
mongoose.set("debug", (collectionName, method, query, doc) => {
console.log(`${collectionName}.${method}`, JSON.stringify(query), doc);
});
const db = mongoose.connection
db.on('error', console.error.bind(console, 'connection error: '))
db.once('open', function() {
console.log('Connected to MongoDB')
app.listen(port, function() {
console.log('API Server Listening on port ' + app.get('port') + '!')
})
})
Backend does return original object; however does not persist and sends no error. I am using MongoDB and Node through WSL2.
Ok, my problem was
I installed Mongo DB as a service on windows
I installed mongodb on WSL2 / Ubuntu at a different time ( I forgot I already installed on windows)
Both using the same port 27107
Using Mongo DB Compass, I can only see the Windows MongoDB which yielded no changes; but data was actually getting sent to the WSL2/Ubuntu MongoDB.
Solution :
Uninstall MongoDB on Windows or run MongoDB in only one platform.
Oh man, this API project is a real huge pain. I got all of these endpoints working yesterday, but as soon as I stared trying to add data to a collection in the database (via Mongo shell), all of a sudden my requests are hanging up. Here is my server:
var express = require('express'),
app = express(),
port = process.env.PORT || 3000;
mongoose = require('mongoose'),
Character = require('./api/models/characterListModels'),
bodyParser = require('body-parser');
mongoose.Promise = global.Promise;
mongoose.connect({ useNewUrlParser: true }, 'mongodb://127.0.0.1:27017/streetfighterdb');
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
var routes = require('./api/routes/characterListRoutes')
routes(app);
app.listen(port);
console.log('Street Fighter RESTful API server started on: ' + port);
Here is my controller
'use strict';
var mongoose = require('mongoose'),
Character = mongoose.model('Characters')
exports.list_all_characters = function (req, res) {
Character.find({}, function (error, character) {
if (error) {
res.send(error);
} else {
res.json(character)
}
})
}
exports.create_a_character = function (req, res) {
var new_character = new Character(req.body);
new_character.save(function (error, character) {
if (error) {
res.send(error);
}
res.json(character);
});
}
exports.get_a_character = function (req, res) {
Character.findById(req.params.characterId, function (error, character) {
if (error) {
res.send(error);
}
res.json(character);
});
}
exports.update_a_character = function (req, res) {
Character.findByIdAndUpdate({
_id: req.params.characterId
}, req.body, {
new: true
}, function (error, character) {
if (error) {
res.send(error);
}
res.json(character);
});
}
exports.delete_a_character = function (req, res) {
Character.deleteOne({
_id: req.params.characterId
}, function (error, character) {
if (error) {
res.send(error);
}
if (!error) {
res.json('Character Successfully Deleted');
}
})
}
Here is my router
'use strict';
module.exports = function(app) {
var characterList = require('../controllers/characterListController');
app.route('/characters')
.get(characterList.list_all_characters)
.post(characterList.create_a_character);
app.route('/characters/:characterId')
.get(characterList.get_a_character)
.put(characterList.update_a_character)
.delete(characterList.delete_a_character);
};
Here is my Model
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var characterSchema = new Schema({
name: {
type: String,
required: true,
}
})
module.exports = mongoose.model('Characters', characterSchema);
Now I have tried a few things.
Removed the specific response and just added a generic res.send('success') and it worked.
I also replaced the {} in the Character.find() method with a [] and it worked (responded with an empty object). For some reason though, none of the other endpoints return responses.
Added a console.log(res) and a console.log(req) and got the logs in the console.
What is going on here? Help!!
Referenced by mongoose offical docs
mongoose.connect('mongodb://username:password#host:port/database?options...', {useNewUrlParser: true});
You are passing the options as first argument, please replace it as offical docs example.
Ok, this is ridiculous, but it turns out that passing the { useNewUrlParser: true } broke it.
I'm trying to use a very basic MongoDB method is to save a document on a database with mongoose.
1.I installed my MongoDB in centos 7
2.Create a database on the Mongo shell using: use mydatabase and insert a document inside it as normal.
3.Install mongoose and make a connection between my nodejs app and the MongoDB:
mongoose.connect('mongodb://localhost:27017/goClass_test', {
useUnifiedTopology: true,
useNewUrlParser: true,
});
4. test the connection and all is fine with:
db.once('open', () => {
console.log('DB Connected');
});
Import the model schema as normal:
var { Classe } = require('../DBModels/GoClassDBModels/classes');
try to add new document like this:
var newClasse = new Classe({
label: 'hello',
level: 'level',
});
newClasse.save()
My Model is:
const mongoose = require('mongoose');
const { Schema } = require('mongoose');
var ObjectId = mongoose.Schema.Types.ObjectId;
var classSchema = new Schema({
directeurId: {
type: ObjectId,
},
label: {
type: String,
},
level: {
type: String,
},
studentNbr: {
type: String,
},
});
var Classe = mongoose.model('Classes', classSchema);
module.exports = { Classe };
SERVER.JS:
const mongoose = require('mongoose');
const express = require('express');
const bodyParser = require('body-parser');
const http = require('http');
const cookieParser = require('cookie-parser');
const _ = require('lodash');
var app = express();
var server = http.createServer(app);
server.listen(80, () => {
console.log('server is started on 80');
});
mongoose.connect('mongodb://localhost:27017/goClass_test', {
useUnifiedTopology: true,
useNewUrlParser: true,
});
console.log(mongoose.connection.host);
console.log(mongoose.connection.port);
let db = mongoose.connection;
db.once('open', () => {
console.log('DB Connected');
});
db.on('error', (err) => {
console.log(err);
});
var { Classe } = require('../DBModels/GoClassDBModels/classes');
const goClasseRouteDirecteur = require('./GOClassRoutes/DirecteurRoutes/subRoutesClass');
app.use(bodyParser.json());
app.use(cookieParser(['lakkini.com']));
app.use(
bodyParser.urlencoded({
extended: false,
})
);
app.use(function (req, res, next) {
res.set(
'Cache-Control',
'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0'
);
next();
});
app.set('view engine', 'hbs');
app.use(express.static('/home/admin/SMS'));
app.use(express.static('/home/admin/assets'));
app.get('/', (req, res) => {
res.render('SMS/dashboard.hbs');
});
app.get('/classes', (req, res) => {
res.render('SMS/classes.hbs');
});
app.get('/inscription', (req, res) => {
res.render('SMS/inscriptions.hbs');
});
app.post('/saveClasse', (req, res) => {
var newClasse = new Classe({
label: 'hello',
level: 'level',
});
console.log('im gonna save the new class');
newClasse.save((err, response) => {
if (err) console.log(err);
else console.log(response);
});
});
The problem is: nothing happened. No document has been inserted and no errors.
Can you suggest to me, please ?
PS: I'm trying to request from an HTTP server without HTTPS.
will that affect my requests nd block the save to the database?
result:
click to see the picture of the result please
Since the whole file was not given for mongoose connection and where save function is called , assuming you have structured it properly i'm giving my answer.
I was able to do this way,
The schema (same as yours) :
const mongoose = require("mongoose");
const { Schema } = require("mongoose");
var ObjectId = mongoose.Schema.Types.ObjectId;
var classSchema = new Schema({
directeurId: {
type: ObjectId,
},
label: {
type: String,
},
level: {
type: String,
},
studentNbr: {
type: String,
},
});
var Classe = mongoose.model("Classes", classSchema);
module.exports = { Classe };
Function to insert:
mongoose.connect("mongodb://localhost:27017/goClass_test", {
useUnifiedTopology: true,
useNewUrlParser: true,
});
var db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
console.log("DB Connected");
var newClasse = new Classe({
label: "hello",
level: "level",
});
newClasse.save();
});
UPDATE:
SERVER.JS
const mongoose = require("mongoose");
const express = require("express");
const bodyParser = require("body-parser");
const http = require("http");
const cookieParser = require("cookie-parser");
const _ = require("lodash");
var app = express();
var server = http.createServer(app);
server.listen(80, () => {
console.log("server is started on 80");
});
mongoose.connect("mongodb://localhost:27017/goClass_test", {
useUnifiedTopology: true,
useNewUrlParser: true,
});
console.log(mongoose.connection.host);
console.log(mongoose.connection.port);
let db = mongoose.connection;
db.once("open", () => {
console.log("DB Connected");
});
db.on("error", (err) => {
console.log(err);
});
var { Classe } = require("./models/Classe");
// const goClasseRouteDirecteur = require('./GOClassRoutes/DirecteurRoutes/subRoutesClass');
app.use(bodyParser.json());
app.use(cookieParser(["lakkini.com"]));
app.use(
bodyParser.urlencoded({
extended: false,
})
);
app.use(function (req, res, next) {
res.set(
"Cache-Control",
"no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0"
);
next();
});
app.set("view engine", "hbs");
// app.use(express.static("/home/admin/SMS"));
// app.use(express.static("/home/admin/assets"));
// app.get('/', (req, res) => {
// res.render('SMS/dashboard.hbs');
// });
// app.get('/classes', (req, res) => {
// res.render('SMS/classes.hbs');
// });
// app.get('/inscription', (req, res) => {
// res.render('SMS/inscriptions.hbs');
// });
app.post("/saveClasse", (req, res) => {
var newClasse = new Classe({
label: "hello",
level: "level",
});
console.log("im gonna save the new class");
newClasse.save((err, response) => {
if (err) console.log(err);
else console.log("RESPONSE" + response);
});
});
I found the issue, but I don't understand why that.
the first structure was:
**
DBModel
classes.js
Server
server.js**
the structure right now:
**
DBModel
classes.js
server.js
**
I make out the server from that folder and all working fine...??
why that?
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