i am trying to retrieve my data from mongoose schema to my route ( say using an app named insomnia just like postman) so evertime i run the route i am getting and empty array, what is wrong with it ?
app.js
const express=require('express');
const bodyparser=require('body-parser');
const app=express();
app.use(bodyparser.urlencoded({extended:false}));
const User=require('./db/models/user').User;
require('./db/mongo');
app.get("/api/user",function(req,res){
User.find().then(function(x){
res.send(x)
console.log(req.body)
})
})
app.listen(3000);
mongo.js
const mongoose = require('mongoose');
db=mongoose.connect('mongodb://localhost/chatter_dev',
{useNewUrlParser:true});
var db = mongoose.connection;
db.once('open', function callback () {
console.log("h");
});
module.exports =mongoose;
user.js
const mongoose=require('mongoose');
const userschema=new mongoose.Schema({
username:{
type:String,
unique:true,
required:true
},
email:{
type:String
},
firstname:String,
lastname:String},{
timestamps:true}
)
exports.User=mongoose.model("User",userschema)
Before doing any work trying to get data OUT, ya gotta get a little data IN. Get into mongo and insert a few records manually. Baby steps can help you diagnose the issue.
can you try this
User.find((err, users) => {
if (err) res.status(500).send(err);
else res.json(users);
});
**App.js**
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const User = require('./models/users');
const options = {
useNewUrlParser: true,
useCreateIndex: true
};
mongoose.connect('mongodb://localhost/chatter_dev', options)
.then(connected => console.log(`Database connection establised`))
.catch(err => console.error(err));
app.get('/api/users', (req, res, next) => {
User.find().then(user => res.send(user)).catch(err => console.error(err));
})
app.listen(3000);
**Users.js (model)**
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
username:{
type:String,
unique:true,
required:true
},
email:{
type:String
},
firstname:String,
lastname:String
}, {timestamps: true});
module.exports = mongoose.model('User', userSchema);
Related
I am trying to create a simple node.js API and I created a router.post method to save data and render the saved data back. But response to the post request is like {"message":""} on hitting this url http://localhost:3000/posts (POST)
body:
{
"title":"My Post",
"description":"this is the description of my first posxsxasxt"
}
Here is the app.js file
const express =require('express');
const app =express();
const mongoose=require('mongoose');
require('dotenv/config');
const bodyParser=require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
//Import Routes
const postsRoute = require('./routes/posts');
//Middleware
app.use(bodyParser.json());
app.use('/posts',postsRoute);
//Routes
app.get('/',(req,res) =>{
res.send('We are on home');
});
//Connect to DB
mongoose.connect(process.env.DB_CONNECTION, { useNewUrlParser: true , useUnifiedTopology: true }, ()=>
console.log("connected to DB!")
);
//how to start listening to server
app.listen(3000);
Here is the code for routes
const express =require('express');
const router=express.Router();
const Post = require('../models/Posts');
router.get('/',(req,res)=>{
res.send('We are on posts');
});
router.get('/specificposts',(req,res)=>{
res.send('We are on posts');
});
router.post('/',(req,res) => {
const post = new Post({
title: req.body.title,
description: req.body.description
});
post.save()
.then( data => {
res.send(data);
})
.catch(err=>{
res.json({message:err});
});
});
module.exports = router;
Here is the schema of the database
const mongoose=require('mongoose');
//create schema
const PostSchema = mongoose.Schema({
title:{
type:String,
required:true
},
description:{
type:String,
required:true
},
date:{
type:Date,
default: Date.now
}
});
module.exports=mongoose.model('Posts', PostSchema);
Go to Atlas UI
Click on Network Access, click on ADD IP ADDRESS and select "allow access from anywhere".
I am creating my first node js api using Mongoose and Express. Facing some issue when i try to post the data it does not work. Postman request never completes and data does not get saved. Please find attached code and help me figure out the issue. Also note that db connection gets established successfully.
//Post.js
const mongoose = require("mongoose");
const PostSchema = mongoose.Schema({
title: {
type: "string",
required: true,
},
description: {
type: "string",
required: true,
},
date: {
type: "Date",
default: Date.now,
},
});
module.exports = mongoose.model("Posts", PostSchema);
// Posts.js => Routes
const express = require("express");
const Post = require("../models/post");
const router = express.Router();
router.get("/", (req, res) => {
res.send("Posts");
});
router.post("/", (req, res) => {
try {
console.log(req.body);
const post = new Post({
title: req.body.title,
description: req.body.description,
});
post
.save()
.then((data) => res.json(data))
.catch((err) => res.json(err));
} catch (error) {
console.log(error);
}
});
module.exports = router;
// app.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
require("dotenv/config");
const bodyParser = require("body-parser");
//Import Routes
const postRoute = require("./routes/posts");
//Middlewares
app.use(bodyParser.json());
//Routes
app.use("/posts", postRoute);
// Connect to db
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log("connected to db !");
}
);
app.listen(3000);
UPDATE
Looks like something is wrong with db connection itself. Below is my connection string. I handled the mongoose connection on error and i get the error shown in screen shot.
mongodb://<dbuser>:<dbpassword>#ds023550.mlab.com:23550/roofapp
Just pasted your code here and is working fine for both post and get.
Are you able to complete the GET request?
How is your project structured?
Make sure you are importing the files correctly.
From your commented out file names you have Post.js with capital letter and you are importing posts. It seems that something is wrong in the imports.
Here is a working solution based on the code you've posted.
Files : app.js - Post.js - Router.js
app.js:
const express = require("express");
const app = express();
const mongoose = require("mongoose");
// require("dotenv/config");
const bodyParser = require("body-parser");
//Import Routes
const postRoute = require("./Router");
//Middlewares
app.use(bodyParser.json());
//Routes
app.use("/posts", postRoute);
// Connect to db
mongoose.connect("mongodb://localhost/test",
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log("connected to db !");
}
);
app.listen(3000);
Post.js
const mongoose = require("mongoose");
const PostSchema = mongoose.Schema({
title: {
type: "string",
required: true,
},
description: {
type: "string",
required: true,
},
date: {
type: "Date",
default: Date.now,
},
});
module.exports = mongoose.model("Posts", PostSchema);
Router.js
const express = require("express");
const Post = require("./Post");
const router = express.Router();
router.get("/", (req, res) => {
res.send("Posts");
});
router.post("/", (req, res) => {
try {
console.log(req.body);
const post = new Post({
title: req.body.title,
description: req.body.description,
});
post
.save()
.then((data) => res.json(data))
.catch((err) => res.json(err));
} catch (error) {
console.log(error);
}
});
module.exports = router;
It’s my first post.
I’m trying to post a data which is object includes “title”,”body”,”snippet” into backend which I use Mongo DB Atlas.
However when I test it on postman, I can’t store those data into a schema which is prepared in model.
The error message:
“ title: MongooseError [ValidatorError]: Path `title` is required.
at new ValidatorError ”
Others(body,snippet) are also null.
app.js:
const express = require('express'),
mongoose = require('mongoose'),
cors = require('cors'),
app = express(),
blogRoutes = require('./routes/blogRoute');
// connect to mongoDB
const dbURI = '';
mongoose.connect(dbURI,{ useNewUrlParser: true,useUnifiedTopology: true } )
.then(result => {
// Listen for requests
app.listen(3000);
})
.catch((err) => console.log(err));
// Middleware & static files
app.use(express.urlencoded({ extended: true }))
// cors
app.use(cors({ origin: true, credentials: true }))
//Blog Router
app.use('/blogs/api',blogRoutes);
//404
app.use((req,res) => {
res.render('404',{ title:'Not Found' });
})
Model file:
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
const blogSchema = new Schema({
title:{
type:String,
required:true
},
snippet:{
type:String,
required:true
},
body:{
type:String,
required:true
},
}, { timestamps:true })
// create model
const Blog = mongoose.model('Blog',blogSchema);
module.exports = Blog;
Controller(store):
// Store
const blog_create_post = async (req,res) => {
const {title,snippet,body} = req.body;
try {
const blog = await Blog.create({ title,snippet,body });
res.status(201).json(blog);
console.log(blog);
} catch (error) {
res.status(400);
}
}
router:
// Store
router.post('/',blogController.blog_create_post)
Even though GET works fine, I’m stuck in this error for a long time on POST method…
I would appreciate if you suggest something.
In your mongoose schema, you have mentioned required for the title as below and while creating a new document mostly it is empty hence the error title: MongooseError [ValidatorError]: Path title is required.
at new ValidatorError
title:{
type:String,
required:true
},
Also, your Controller is catering title properly.
It can be the way you are sending data from the postman if you are sending raw and JSON then add below middleware comment
app.use(express.json());
i created a mongodb with a name userInfo with collection name "info" in the terminal and i created a schema in models/user_info.js.And i am not getting any values from the database at all.
my userInfo db has name,studentId,dept
My view engine is jade/pug I am trying to iterate and display the values from the database. I am not getting an error but its not displaying the values. Thanks for the help!
app.js
const express= require('express');
const path = require('path')
const mongoose = require('mongoose')
const bodyParser = require('body-parser')
mongoose.connect('mongodb://localhost/userInfo')
let db = mongoose.connection;
db.on('error',(error) => console.log(error));
db.once('open',() => console.log('Connected to Mongodb'))
const app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
let UserInfo = require('./models/user_info')
app.set('views',path.join(__dirname,'views'))
app.set('view engine','pug')
app.get('/',(req,res) => {
UserInfo.find({},function(err,info){
if(err){
console.log(err);
}else{
res.render('tabel',{
title:'user report',
info:info
});
}
})
})
user_info.js //shema
let mongoose = require('mongoose');
//Userinfo Schema
let userInfoSchema = mongoose.Schema({
name:{
type:String,
required:true
},
studentID:{
type:String,
required:true
},
dept:{
type:String,
required:true
}
});
let UserInfo = module.exports = mongoose.model('UserInfo',userInfoSchema);
In your model, you are pointing the collection name UserInfo, but your data are in 'info' collection.
So, change the collection name explicitly in your model.
Your user_info.js (schema) should be,
let mongoose = require('mongoose');
let userInfoSchema = mongoose.Schema({
name:{
type:String,
required:true
},
studentID:{
type:String,
required:true
},
dept:{
type:String,
required:true
}
});
let UserInfo = module.exports = mongoose.model('UserInfo', userInfoSchema, 'info');
In the last line, I pass the third argument, to indicate the collection name to info.
I am getting cyclic dependency error.
I have set the connections in index.js file, set the model in blogModel.js file and am requiring those in the blogController.js file. When I run node index.js, I get output all the way till db conn success but then the cyclic dependency error comes up.
I tried mongoose.model even with the module.export statement, still the error remains.
This is the schema file:
const mongoose = require ('mongoose');
const Schema = mongoose.Schema;
let blogSchema = new Schema({
blogId:{
type:String,
unique:true
},
title:{
type:String,
default:''
},
description:{
type:String,
default:''
},
bodyHtml:{
type:String,
default:''
},
view:{
type:Number,
default:0
},
isPublished:{
type:Boolean,
default:false
},
category:{
type:String,
default:''
},
author:{
type:String,
default:''
},
tags:[],
created:{
type:Date,
default:Date.now
},
lastModified:{
type:Date,
default:Date.now
}
});
// no export statement here, mongoose.model handles that
//mongoose.model('Blog',blogSchema);
module.exports = mongoose.model('Blog',blogSchema)
this is the controller file
const express = require ('express');
const mongoose = require ('mongoose');
const shortid = require ('shortid');
//const BlogModel = mongoose.model("Blog");
const BlogModel = require('./../models/blogModel')
module.exports = {
helloworld: helloworld,
printExample : printExample,
testRoute : testRoute,
testQuery : testQuery,
testBody : testBody,
}
And finally the index.js file:
//importing the module for use
const express = require('express');
const fs = require('fs');
const appConfig = require('./config/appConfig');
console.log(JSON.stringify(appConfig));
const blog = require('./routes/blogRoute.js');
//outputs in terminal -- console.log(appConfig);
//creating an instance of express
const app = express();
const bodyParser = require('body-parser');
//middlewares
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:false}));
let helloFunc = (req, res) => res.send('Hello World!');
app.get('/hello',helloFunc);
app.get('/',helloFunc);
//bootstrap route using routes folder
let routesPath = './routes';
fs.readdirSync(routesPath).forEach(function(file) {
if(~file.indexOf('.js')){
console.log(~file.indexOf('.js'));
console.log("including the file");
console.log(routesPath+ '/' +file)
console.log(file);
let route = require(routesPath + '/' + file);//why this way?
//setting
route.setRouter(app);
}
});
const mongoose = require('mongoose');
//path for model of db
let modelsPath = './models'
fs.readdirSync(modelsPath).forEach(function(file) {
if(~file.indexOf('.js')){
require(modelsPath +'/' + file);
console.log(file);
}
});
//const blogSchema = require('./models/blogModel')//
//blogSchema = blogSchemaRoute.blogSchema;
app.listen(appConfig.port, function(){
console.log('Blog app listening on port 3000!');
//creating mongodb connection
});
let db = mongoose.connect(appConfig.db.uri)//('mongodb://localhost:27017')
mongoose.connection.on('error',function(err){
console.log("database connection error");
console.log(err);
});
mongoose.connection.on('open',(err)=>{
if (err){
console.log("database connection error");
console.log(err);
}
else{
console.log("db conn success");
}
});
When I run node index.js, I get cyclic dependency error:
C:\Users\IBM_ADMIN\Desktop\JS\5 Node\node_Basics>node index.js
{"port":3000,"allowedCorsOrigin":"*","environment":"dev","db":{"uri":"mongodb://
localhost:27017/blogDB"},"apiVersion":"/api/v1"}
-10
including the file
./routes/blogRoute.js
blogRoute.js
blogModel.js
Blog app listening on port 3000!
db conn success
C:\Users\IBM_ADMIN\Desktop\JS\5 Node\node_Basics\node_modules\mongoose\lib\utils
.js:452
throw err;
^
Error: cyclic dependency detected
at serializeObject (C:\Users\IBM_ADMIN\Desktop\JS\5 Node\node_Basics\node_mo
dules\bson\lib\bson\parser\serializer.js:333:34)
at serializeInto (C:\Users\IBM_ADMIN\Desktop\JS\5 Node\node_Basics\node_modu
les\bson\lib\bson\parser\serializer.js:937:17)