This is my server.js. When I run node server.js then use PostMan to post json, it gives me the following error.
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
app.use(bodyParser.json())
app.get('/api/posts', function(req, res) {
res.json([
{
username: '#rodandrew95',
body: 'node rocks!'
}
])
})
app.listen(3000, function() {
console.log('Server listening on', 3000)
})
var Post = require('./models/post')
app.post('/api/posts', function(req, res, next) {
// console.log('post received')
// console.log(req.body.username)
// console.log(req.body.body)
// res.sendStatus(201)
var post = new Post({
username: req.body.username,
body: req.body.body
});
post.save(function (err, post) {
if (err) { return next(err) }
res.sendStatus(201).json(post)
})
})
The error:
(node:6863) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
ValidationError: Post validation failed
at MongooseError.ValidationError (/Users/andrewrodrigues/Desktop/write_modern/ch_1/node_modules/mongoose/lib/error/validation.js:23:11)
at model.Document.invalidate (/Users/andrewrodrigues/Desktop/write_modern/ch_1/node_modules/mongoose/lib/document.js:1486:32)
at /Users/andrewrodrigues/Desktop/write_modern/ch_1/node_modules/mongoose/lib/document.js:1362:17
at validate (/Users/andrewrodrigues/Desktop/write_modern/ch_1/node_modules/mongoose/lib/schematype.js:705:7)
at /Users/andrewrodrigues/Desktop/write_modern/ch_1/node_modules/mongoose/lib/schematype.js:742:9
at Array.forEach (native)
at SchemaString.SchemaType.doValidate (/Users/andrewrodrigues/Desktop/write_modern/ch_1/node_modules/mongoose/lib/schematype.js:710:19)
at /Users/andrewrodrigues/Desktop/write_modern/ch_1/node_modules/mongoose/lib/document.js:1360:9
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
I'm trying to learn the MEAN stack through "Write Modern Web Apps with the MEAN Stack" but I'm running into issues all the time, even when I follow the code and instructions exactly. Can anyone help understand this error, and possibly recommend some good resources for learning the mean stack?
This error is triggered because you have provided a mongoose validation in
your schema (in /models/post) and that validation is failing.
For instance, if you provided your model like this :
var postSchema = new Schema({
"username": String,
"body": String,
"email": {
type: String,
required: true
}
});
var Post = mongoose.model('Post', postSchema);
This would fail because email required validator is not respected. Find a full list of validators here.
Side note : res.sendStatus(201).json(post) will set the json body and content-type header after sending a response with 201 status. To send both use :
res.status(201).json(post)
Related
I'm currently creating a new API with MongoDB and Express, and I'm currently having this issue "Operation disneys.insertOne() buffering timed out after 10000ms." I'm currently using route.rest to test my API.
However, I don't know what I'm currently doing wrong, could someone take a look at my Github Repository ?
This is the way that I setup my API calls:
const express = require("express");
const router = express.Router();
const Disney = require("../models/disneyCharacter");
// Getting all character
router.get("/", async (req, res) => {
try {
const character = await Disney.find();
res.json(character);
} catch (err) {
res.status(500).json({ message: err.message });
}
});
// Getting one Character
router.get("/:id", getCharacter, (req, res) => {
res.json(res.character);
});
// Creating new Character
router.post("/", async (req, res) => {
const character = new Disney({
name: req.body.name,
details: req.body.details,
});
try {
const newCharacter = await character.save();
res.status(201).json({ newCharacter });
} catch (err) {
res.status(400).json({ message: err.message });
}
});
// Updating one character
router.patch("/:id", getCharacter, async (req, res) => {
if (req.body.name != null) {
res.character.name = req.body.name;
}
if (req.body.details != null) {
res.character.details = req.body.details;
}
try {
const updateCharacter = await res.character.save();
res.json(updateCharacter);
} catch (err) {
res.status(400).json({ message: err.message });
}
});
// Deleting one character
router.delete("/:id", getCharacter, async (req, res) => {
try {
await res.character.remove();
res.json({ message: "Deleted character" });
} catch (err) {
res.status(500).json({ message: err.message });
}
});
async function getCharacter(req, res, next) {
let character;
try {
character = await character.findById(req.params.id);
if (character == null) {
return res.status(404).json({ message: "Cannot find character" });
}
} catch (err) {
return res.status(500).json({ message: err.message });
}
res.character = character;
next();
}
module.exports = router;
My parameters are the following:
const mongoose = require("mongoose");
const disneyCharacter = new mongoose.Schema({
name: {
type: String,
required: false,
},
details: {
type: String,
required: false,
},
subscribeDate: {
type: Date,
required: true,
default: Date.now,
},
});
module.exports = mongoose.model("Disney", disneyCharacter);
This is my API call:
Post http://localhost:3000/disneyCharacter
Content-Type: application/json
{
"name": "Mickey Mouse",
"details": "First Character from Disney"
}
Please let me know if you have any other questions or concerns.
try this out
How to solve Mongoose v5.11.0 model.find() error: Operation `products.find()` buffering timed out after 10000ms"
Also, your API call seem to have a problem, It should be disneyCharacters instead of disneyCharacter.
Also, probably setup a local database first instead of using process.env.DATABASE_URL.
Actually i was also getting the same error.
steps i performed to solve this error are
while creating database in mongodb
allow access from anywhere (ip configuration)
choose the nearest server
this solved my problems :)
In my application the same error message was thrown.
The difference is, that I am using MongoDB Atlas, instead of a local MongoDB.
Solution:
After added "+srv" to the URL scheme is issue was gone:
const mongoose = require("mongoose");
mongoose.set('useUnifiedTopology', true);
mongoose.set('useNewUrlParser', true);
mongoose.connect("mongodb+srv://user:password#host/dbname")
.then( () => console.log("connected to DB."))
.catch( err => console.log(err));
Dependencies in package.json:
"dependencies": {
"mongoose": "^5.11.12",
}
MongoDB Version 4.2.11
The connection string is given in the MongoDB Atlas frontend: -> Data Storage -> Cluster -> connect -> Connect your application
There you can find some code snippets.
I faced the same error. I am using mongoDB Atlas and not the local one. What worked for me was to remove the options in the .connect method (I am using mongoose for connecting to mongodb).
Previous code (that caused the error)
mongoose.connect(
"" + process.env.DB_URL,
{ useUnifiedTopology: true, useNewUrlParser: true, useFindAndModify: false },
() => { console.log("Connected to DB"); }
)
Just remove the code inside { } in this method.
mongoose.connect(
"" + process.env.DB_URL,
{ },
() => { console.log("Connected to DB"); }
)
I get this error I found Solution
Operation insertMany() buffering timed out after 10000ms"
install
API Call Server File
npm i dotenv
import express from 'express';
import mongoose from 'mongoose';
import data from './data.js';
import userRouter from './routers/userRouter.js';
import dotenv from 'dotenv';
import config from './config.js';
dotenv.config();
const mongodburl = config.MONGODB_URL
const app = express();
mongoose.connect(mongodburl, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex:true,
}).then(() => console.log('Hurry Database Connected'));
Router File
install express async handler
npm i express-async-handler
import express from 'express';
import expressAsyncHandler from 'express-async-handler';
import data from '../data.js';
import User from '../models/userModel.js';
const userRouter = express.Router();
userRouter.get(
'/seed',
expressAsyncHandler (async(req,res)=>{
//await User.remove({});
const createdUsers = await User.insertMany(data.users);
res.send({ createdUsers });
})
);
Remove these two:
useCreateIndex: true,
useFindModify: false,
and put this:
useNewUrlParser: true,
useUnifiedTopology: true
final examples:
mongoose.connect(process.env.MONGODB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true
}, err => {
if(err) throw err;
console.log('Connected to mongodb')
})
Try this way too:
In order to solve the error i kept the code in async await function. After successfully connected the db then only we can do the CRUD operation. Nodejs follows the single thread execution i.e line by line executed. if any line is waiting for any request node automatically go to the next line and execute it first. So if a line depends on a request, put in async await function.
Add ssl=true in the URL Scheme as shown in below .
mongodb+srv://:#node-rest-courses.4qhxk.mongodb.net/myFirstDatabase?retryWrites=true&w=majority&ssl=true
in my code, only have removed parameters ssl, i am working with database in digitalOcean, my code is:
mongoose.Promise=global.Promise;
mongoose.connect(process.env.MONGO_URI,{
useNewUrlParser: true,
useUnifiedTopology: true,
ssl: true,
// tlsCAFile: mongoCertPath, ----> you should remove this line
socketTimeoutMS:43200000,
}).then(
()=>{ console.log('conected to digitalOcean mongoDB: db_CRM'); },
err=>{console.log('erro to connect digitalOcean mongoDB:'+err);}
);
The solution to this problem is with the route.rest file since this file is not doing something correctly. For the same reason, I went ahead and create a new project in Mongo DB to set up a cluster and create the database.
Also, I tested by using POSTMAN
Everything is working correctly now!
It is a connection problem with mongodb server.
You can use IP address instead of domain/server name of your server in mongoose.connect().
In my case even localhost is not working so I replace 127.0.0.1 and everything works fine so I go back and change host file in my windows.
This is my server.js file code . I am trying to push the JSON content in the user object , but i am getting following error. Please tell me where i am going wrong.
const express = require('express')
const app = express()
const bcrypt = require('bcrypt')
const bodyParser = require('body-parser')
app.use(express.json())
const users = []
app.get('/users', (req, res) => {
JSON.stringify(users)
res.json(users)
})
app.post('/users', (req, res) => {
const user = {
name: req.body.name,
password: req.body.password
}
users.push(user)
res.status(201).send()
})
app.listen(3000, console.log("server started"));
I used an extension in VS code called REST client.
GET http: //localhost:3000/users
#####
POST http: //localhost:3000/users
Content-Type: application/json
{
"name": "Tanay",
"password": "password"
}
When I'm firing POST request it shows the error - SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at parse (C:\Users\TANAY RAJ\Desktop\nodePassport\Wsimplified\node_modules\body-parser\lib\types\json.js:89:19)
at C:\Users\TANAY RAJ\Desktop\nodePassport\Wsimplified\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (C:\Users\TANAY RAJ\Desktop\nodePassport\Wsimplified\node_modules\raw-body\index.js:224:16)
at done (C:\Users\TANAY RAJ\Desktop\nodePassport\Wsimplified\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (C:\Users\TANAY RAJ\Desktop\nodePassport\Wsimplified\node_modules\raw-body\index.js:273:7)
at IncomingMessage.emit (events.js:322:22)
at endReadableNT (_stream_readable.js:1187:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
Can be something wrong with the user variable. Can you check this:
const user={'name':req.body.name,'password':req.body.password}
Update
I tried out:
var data = [];
const user={'name':"Deshan",'password':"password"}
data.push(user);
console.log(data);
And the result was as follow:
[ { name: 'Deshan', password: 'password' } ]
So it maybe a problem with the request data.
I want to add data to my mongodb collection collection name is 'post' ,
here is my server.js code
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
app.use(bodyParser.json());
Post = require('./www/js/models/post.js');
mongoose.connect('mongodb://localhost/BlogDB'); //connect to mongoose
var db = mongoose.connection;
app.post('/api/post',function (req, res) {
var post = req.body;
Post.addPost(post,function (error, post) {
if(error){
throw error;
}
res.json(post);
})
});
this is my post schema-
var mongoose = require('mongoose');
/// Post schema
var postSchema = mongoose.Schema({
title: {
type: String,
required: true
},
description: {
type: String
},
author: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
}, {collection: 'post'});
var Post = module.exports = mongoose.model('Post', postSchema);
//add post
module.exports.addPost = function (post, callback) {
Post.create(post,callback);
};
when i send post request from RestEasy chrome extension then throw this error msg
throw er; // Unhandled 'error' event
^
ValidationError: Post validation failed
at MongooseError.ValidationError (F:\Project\Private\Blog\node_modules\mongoose\lib\error\validation.js:23:11)
at model.Document.invalidate (F:\Project\Private\Blog\node_modules\mongoose\lib\document.js:1501:32)
at F:\Project\Private\Blog\node_modules\mongoose\lib\document.js:1377:17
at validate (F:\Project\Private\Blog\node_modules\mongoose\lib\schematype.js:705:7)
at F:\Project\Private\Blog\node_modules\mongoose\lib\schematype.js:742:9
at Array.forEach (native)
at SchemaString.SchemaType.doValidate (F:\Project\Private\Blog\node_modules\mongoose\lib\schematype.js:710:19)
at F:\Project\Private\Blog\node_modules\mongoose\lib\document.js:1375:9
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
[nodemon] app crashed - waiting for file changes before starting...
ValidationError: Post validation failed
Mongoose tells you that the data you're inserting in Mongo is not valid as it does not satisfy the schema you built. So check carefully what you're inserting.
It seems schema validation error for post data JSON from Mongoose.,
{
"title": "Javascript",
"description": "Javascript story",
"author": "Karthikeyan.A",
"date:: "Tue Apr 04 2017 13:56:23 GMT+0530 (IST)"
}
I'm trying to do a POST request using express on node.js and mongoose for mongoDB but using Postman to get data gives me this error:
Error at MongooseError.ValidationError
(C:\Users\Matteo\Desktop\app1\node_modules\mongoose\lib\error\validation.js:22:16)
at model.Document.invalidate
(C:\Users\Matteo\Desktop\app1\node_modules\mongoose\lib\document.js:1162:32)
at
C:\Users\Matteo\Desktop\app1\node_modules\mongoose\lib\document.js:1037:16
at validate
(C:\Users\Matteo\Desktop\app1\node_modules\mongoose\lib\schematype.js:651:7)
at
C:\Users\Matteo\Desktop\app1\node_modules\mongoose\lib\schematype.js:679:9
at Array.forEach (native) at
SchemaString.SchemaType.doValidate
(C:\Users\Matteo\Desktop\app1\node_modules\mongoose\lib\schematype.js:656:19)
at
C:\Users\Matteo\Desktop\app1\node_modules\mongoose\lib\document.js:1035:9
at process._tickCallback (node.js:355:11)
I paste here my server.js file
var express = require('express')
var bodyParser = require('body-parser')
var mongoose = require('mongoose');
var app = express()
app.use(bodyParser.json())
mongoose.connect('mongodb://localhost/social', function(){
console.log('mongodb connected')
})
var postSchema = new mongoose.Schema ({
username : { type: String, required: true },
body : { type: String, required: true },
date : { type: Date, required: true, default: Date.now}
})
var Post = mongoose.model('Post', postSchema)
app.get('/api/posts', function(req, res, next){
Post.find(function(err, posts){
if(err) { return next(err) }
res.json(posts)
})
})
app.post('/api/posts', function(req, res, next){
var post = new Post({
username : req.body.username,
body : req.body.body
})
post.save(function(err, post){
if(err){ return next(err) }
res.json(201, post)
})
})
app.listen(3000, function(){
console.log('Server listening on', 3000)
})
Can anyone help me or it is a problem of mongoose?
I got a similar error today, and reading the docs helped me through.
The doc says:
Defining validators on nested objects in mongoose is tricky, because nested objects are not fully fledged paths.
var personSchema = new Schema({
name: {
first: String,
last: String
}
});
A schema like the above will throw similar error like in your question.
The docs points out the workaround:
var nameSchema = new Schema({
first: String,
last: String
});
personSchema = new Schema({
name: {
type: nameSchema,
required: true
}
});
Source: http://mongoosejs.com/docs/validation.html
in Postman, to test HTTP post actions with raw JSON data, need to select the raw option and also set the header parameters( select header parameter in postman and add in key:value feild which is given below ).
Content-Type: application/json
by default, it comes with Content-Type: text/plain which need to replace with Content-Type: application/json
I think it's Mongoose Validation issue, req.body is actually a JSON formatted-data, console.log(req.body.username) returns the username value. To be general, try to use req.body, please make use to fill-out the required fields upon submission.
app.post('/api/posts', function(req, res, next){
var post = new Post(req.body);
post.save(function(err, post){
if(err){ return next(err) }
res.json(post)
})
})
Better to handle MongooseError.ValidationError when a user fails to fill-in required fields. Try to review your Mongoose Model.
I am building my first express.js application and I have run into my first hurdle.
I have a very simple set up.
routes in app.js:
app.get('/', routes.index);
app.get('/users', user.list);
app.get('/products', product.all);
app.post('/products', product.create);
route(controller) in routes/product.js
var Product = require('../models/product.js');
exports.create = function(req, res) {
new Product({ name: req.query.name, description: req.query.description }).save();
};
exports.all = function(req, res) {
Product.find(function(err, threads) {
if (err) {
res.send('There was an error: ' + err)
}
else {
res.send(threads)
}
});
}
Product model in models/product.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var productSchema = new Schema({
name: String,
description: String
});
module.exports = mongoose.model('Product', productSchema);
I have tried sending post requests with both Postman (chrome extension) as well as Curl. I have noticed that both seem to hang after sending the request, as if waiting for a response, i'm no http expert but I assumed a post would not have a response? But perhaps it responds with whether it was successful or not?
my sample requests:
http://0.0.0.0:3000/products?name=Cool, http://0.0.0.0:3000/products?name=Cool%Product&description=Allo%there%Soldier!
After sending the post and then sending a get request to http://0.0.0.0:3000/products I get an array of objects like so:
{
"_id": "52e8fe40b2b3976033ae1095",
"__v": 0
},
{
"_id": "52e8fe81b2b3976033ae1096",
"__v": 0
},
These are equal to the number of post requests I have sent, indicating to me that the server is receiving the post and creating the document/file, but not actually passing the parameters in.
Some help here would be excellent!
EDIT: It seems the code above is fine, I think I may have forgotten to restart my node server after having made some changes (Doh!), the restart fixed the issue
there is something like an http-request lifecycle, and of course an post has a response.
probably something like a 200 if your insert worked and a 404 if not!
you need to send a response in your create method:
exports.create = function(req, res) {
new Product({ name: req.query.name, description: req.query.description }).save();
res.send('saved');
};
Your post needs a response. You could do something like
var newProduct = new Product({ name: req.query.name, description: req.query.description });
newProduct.save(function(err, entry) {
if(err) {
console.log(err);
res.send(500, { error: err.toString()});
}
else {
console.log('New product has been posted.');
res.send(JSON.stringify(entry));
}
});