Mongoose not displaying data from mongoDB - node.js

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.

Related

I can't store data into MongoDB(Atlas) on Postman (Node.js with express)

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());

express: req.body is empty on PUT request (findOneAndReplace)

i have a strange behavior on my express/node/mongodb server app,
seems that only when i call a PUT request with findOneAndReplace method, this one look like empty.
In fact i have this error message for validation method:
here the code:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
const methodOverride = require('method-override');
const session = require('express-session');
const passport = require('passport');
const logger = require('morgan');
const cors = require('cors');
//MODEL
const Clienti = require('./model/clienti');
app.use(bodyParser.urlencoded({limit: '10mb', extended: false}));
app.use(methodOverride('_method'));
app.use(bodyParser.json({limit: '10mb'}));
//UPDATE
app.put('/api/aggiorna_cliente/:id', function(req, res, next) {
console.log(JSON.stringify(req.body)) --> N.B. i have the correct body rendition here
console.log(JSON.stringify(req.params.id))
Clienti.findOneAndReplace(
{ _id:req.params.id },
{
address:req.body.address,
brand:req.body.brand,
cap:req.body.cap,
city:req.body.city,
civico:req.body.civico,
email:req.body.email,
fiscalcode:req.body.fiscalcode,
provincia:req.body.provincia,
utente:req.body.utente
},
function (err, post) {
if (err) return next(err);
res.json(post);
});
});
here the CLIENTI model
const mongoose = require('mongoose');
const clientiSchema = mongoose.Schema({
utente:{
type: String,
required:true
},
cap:{
type: Number,
required:true
},
civico:{
type: String,
required:true
},
city:{
type: String,
required:true
},
address:{
type: String,
required:true
},
fiscalcode:{
type:String,
required:true
},
email:{
type:String,
required:true
},
brand:{
type:String,
required:true
},
provincia:{
province: String,
sigle: String
}
});
const Clienti = mongoose.model('Clienti',clientiSchema);
module.exports = Clienti
as you can see quite all the fields are "required", that cause the validation problem on the picture above.
But if i remove the rquired field, all the data is empty (except for id)
last the way that i use service in angular
updateCustomer(customer){
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.put(this.UpdateCustomer+'/'+customer._id, JSON.stringify(customer), {headers: headers})
.map((response: Response) => response.json())
}
what could it be?
Thank you for your time

Retreiving data from mongoose schema into my node js project

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);

Cannot access static functions in mongoose model . the error says "unexpected token . "

I have my mongoose schema defined in user.js file.
//user.js
const mongoose = require('mongoose');
const validator = require('validator');
const jwt = require('jsonwebtoken');
let userSchema = new mongoose.Schema({
email: {
type:String,
require:true,
trim:true,
minlength: 1,
unique:true,
validate:{
validator: validator.isEmail
,
message: '{value} is not valid',
}
},
password:{
type:String,
required:true,
minlength:6
},
tokens: [{
access:{
type:String,
required:true
},
token:{
type:String,
required:true
}
}]
})
userSchema.statics.findByToken = function(token){
console.log('token');
let User = this;
console.log("this is: ",User);
let decoded;
try{
decoded = jwt.verify(token,'abc123')
}catch(e){
return Promise.reject();
}
return User.findOne({
_id: decoded._id,
'tokens.token': token,
'tokens.access': 'auth'
})
}
const User = mongoose.model('User', userSchema );
module.exports = {
User: User,
}
I am trying to import it into a seperate file and call the function findByToken inside app.get("users/me") route . The function is meant to receive the token as an argument and find the document associated with that token from the database.
The code is pasted below
//server.js
const express = require('express');
const {User} = require('./models/user.js');
const bodyParser = require('body-parser')
let app = express();
app.use(bodyParser.json());
process.env.port = 3000;
const PORT = process.env.port;
app.get('/users/me',(req,res)=>{
let token = req.header('x-auth')
User.findByToken(token).then((user)=>{
if(!user){
return Promise.reject();
}
res.status(200).send(req.user);
}).catch(e)=>{
res.status(401).send();
}
})
app.listen(PORT,()=>{
console.log('listening to port: ',PORT)
})
When I run the code I get this error.
module.exports = User = mongoose.model('users', UserSchema);
I don't see an export expression in your user.js

How do I remove cyclic dependency error in mongo? I am using mongoose along with express

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)

Resources