Not able to view JSON data - javascript

I have below code in app.js.
var express = require("express");
var app = express();
var port = 3001;
app.get("/", (req, res) => {
res.send("success");
});
app.listen(port, () => {
console.log("Server listening on port " + port);
});
var mongoose = require('mongoose');
mongoose.createConnection('mongodb://localhost:27017/mydb');
var Schema = mongoose.Schema;
var productSchema=new Schema({
created_at: String,
id: Number
});
const Products = mongoose.model("myc",productSchema);
app.get('/',function(req,res){
Products.find({},function(err,products){
res.json(products)
});
})
// module.exports = app;
I have created mongodb database mydb and myc as collection which contents the document.
When i type localhost:3000, I dont see the JSON data stored in Mongodb its shows only blank page. Please help

var express = require("express");
var app = express();
var port = 3001;
var mongoose = require('mongoose');
mongoose.createConnection('mongodb://localhost/mydb');
var Schema = mongoose.Schema;
var productSchema=new Schema({
created_at: String,
id: Number
});
const Products = mongoose.model("myc",productSchema);
app.get('/',function(req,res){
Products.find({},function(err,products){
if(!err){
res.json(products)
}
else{
res.send(err)
}
});
})
app.listen(port, () => {
console.log("Server listening on port " + port);
});
module.exports = app;

Related

Mongoose .find is not a function?

I am using mongoose version ^5.10.2 and I've been able to save data to the mongo Atlas database BUT I can not get the data down. When I try using:
const mongoose = require('mongoose');
const express = require('express');
{
const config = require("./config.json")
var token = config.token;
var prefix = config.prefix;
var botName = config.botName;
}
const server = require('./server.js');
server();
var Schema = mongoose.Schema;
var SomeModelSchema = new Schema({
modName: String,
modUrl: String
});
// Compile model from schema
var SomeModel = mongoose.model('SomeModel', SomeModelSchema);
setInterval(function () {
// Create an instance of model SomeModel
var awesome_instance = new SomeModel({ 'ModName': 'Kiddions mod menu', 'modUrl': 'https://www.unknowncheats.me/forum/downloads.php?do=file&id=27946' });
console.log('---Direct info---');
console.log('Name: ' + awesome_instance.ModName);
console.log('URL: ' + awesome_instance.modUrl);
// Save the new model instance, passing a callback
awesome_instance.save(function (err) {
if (err) return handleError(err);
// saved!
});
awesome_instance.find({}, function(err, data){
console.log(">>>> " + data );
});
}, 2000);
Server.js code:
const express = require('express');
const connectDB = require('./DB/Conncection');
const app = express();
module.exports = function server() {
connectDB();
app.use(express.json({ extended: false }));
app.use('/api/userModel', require('./Api/Mod'));
const Port = process.env.Port || 3030;
app.listen(Port, () => {
console.log('Server started')
});
}
Connection.js code:
const mongoose = require('mongoose');
const URI =My database";
const connectDB = async () => {
await mongoose.connect(URI, {
useUnifiedTopology: true,
useNewUrlParser: true
});
console.log('DB connected..!');
};
module.exports = connectDB;
It fails... I get the bug:
Server started
DB connected..!
---Direct info---
Name: undefined
URL: https://www.unknowncheats.me/forum/downloads.php?do=file&id=27946
C:\Users\zssho\Desktop\Fiverr Gigs\the_mcs - GTA modding\Discord bot\src\bot.js:45
**awesome_instance.find({}, function(err, data){
^
TypeError: awesome_instance.find is not a function
at Timeout._onTimeout (C:\Users\zssho\Desktop\Fiverr Gigs\the_mcs - GTA modding\Discord bot\src\bot.js:45:22)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7)
I have used this as a function for a while but it stopped working recently. Could it be because I updated mongoose?
awesome_instance is a document .find is a method present in collection/models so try
SomeModel.find({}, function(err, data){
console.log(">>>> " + data );
});

Mongoose saves just '_v' and '_id'

I'm trying to add book to MongoDB and try to post with Postman it just saves _id and _v. I read a lot of answers here but neither was helpful. Get books works good but I inserted a book from command prompt.
Is there any other method to save it ?
Here is the code of api.js file:
onst express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
var Book = require('../models/book');
//MONGODB CONNECTION
mongoose.connect('mongodb://127.0.0.1:27017/books' ,({useMongoClient: true}));
mongoose.connection.on('connected', () => {
console.log('Successfully connected to MongoDB');
});
mongoose.connection.once('error', (err) =>{
console.log('Error: '+ err);
});
//Get books
router.get('/books', function(req, res) {
Book.find(function(err, books) {
if (err) {
res.send(err);
} else
res.json(books);
});
});
//Post books
router.post('/books', (req,res) => {
let newBook = new Book (req.body);
newBook.name = req.body.name,
newBook.author = req.body.author,
newBook.pages = req.body.pages,
newBook.save((err, newBook) => {
if (err){
console.log(err);
} else {
res.json(newBook);
}
});
});
module.exports = router;
Here is the code of the model file:
const mongoose = require('mongoose');
var schema = mongoose.Schema;
var bookSchema = new schema ({
name: String,
author: String,
pages: Number
});
module.exports = mongoose.model('book', bookSchema, 'books');
And code of the server file:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const api = require('./server/routes/api');
const app = express();
//SERVER
const port = 3000;
app.listen(3000, () => {
console.log('Server started on port '+port)
});
// BODYPARSER
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
//API
app.use('/api', api);
// ROUTES
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});

Nodejs/express - Router.use() requires middleware function but got a ' + gettype(fn));

I'm new to back-end development with node and express. i'm trying to make a back-end for a simple blog with posts and user authentication to use later in an angular 4 app.
On the "Posts" end, after testing with chrome's addon "Postman", all seems to work fine but when i started working on the "Users" side it keeps throwing off the error:
"Router.use() requires middleware function but got a ' + gettype(fn));"
When i try to run the server. The code is below:
app.js
//Imports
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const mongo = require('mongodb');
const mongoose = require('mongoose');
const passport = require('passport');
const cors = require('cors');
const config = require('./config/database');
//initialize App
var app = express();
//Setting port
var port = 3000;
//initialize cors
app.use(cors());
//Set static folder
app.use(express.static(path.join(__dirname,'../client/src')));
//initialize body parser
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
//Root route
app.get('/', function(req,res) {
res.send('Welcome to my API');
});
//Listen to port
app.listen(port, function () {
console.log('Server is running on post: ' + port);
});
//connection to DB
mongoose.connect(config.database);
mongoose.connection.on('connected', function () {
console.log('Connected to database' + config.database);
});
mongoose.connection.on('error', function (err) {
console.log('Database error' + err);
});
//Models
var Post = require('./models/post');
var User = require('./models/user');
//Routes
var postRouter = require('./routes/posts')(Post);
var userRouter = require('./routes/users')(User);
//Initialize routes
app.use('/api/posts', postRouter);
app.use('/api/users', userRouter);
models/user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userModel = new Schema({
name: {type: String},
email: {type: String, required:true},
username: {type: String, required:true},
password: {type: String, required:true}
});
module.exports = mongoose.model('Users',userModel);
routes/users.js
var express = require('express');
var passport = require('passport');
var jwt = require('jsonwebtoken');
var userRoutes = function(User) {
var UserRouter = express.Router();
var userController = require('../controllers/userController')(User);
//Register
UserRouter.route('/register').post(userController.post);
//Authenticate
UserRouter.route('/authenticate').get();
//Profile
UserRouter.route('/profile').get();
};
module.exports = userRoutes;
controllers/userController.js
var userController = function(User) {
var post = function(req,res) {
var bcrypt = require('bcryptjs');
//creating new instance of model and pass the bodyParser
var user = new User(req.body);
if(!req.body.username) {
res.status(400);
res.send('Name is required');
}
else if (!req.body.password) {
res.status(400);
res.send('Password is required');
}
else if (!req.body.email) {
res.status(400);
res.send('Email is required');
}
else {
bcrypt.hash(user.password, function (err, hash) {
user.password = hash;
});
//saving in db
user.save();
//status 201 means created
res.status(201);
//send result
res.send(user);
}
};
return {
post: post
};
};
module.exports = userController;
The problem occurs when i initialize the users route with
app.use('/api/users', userRouter);
in app.js
"Router.use() requires middleware function but got a ' + gettype(fn));"
the error comes from this line :
app.use('/api/users', userRouter);
app.use need a path and a middleware function. Here your returning
a simple function, not a middleware, that's why you got the error.
in routes/users.js you just have to return the express.Router middleware function.
var express = require('express');
var passport = require('passport');
var jwt = require('jsonwebtoken');
var userRoutes = function(User) {
var UserRouter = express.Router();
var userController = require('../controllers/userController')(User);
//Register
UserRouter.route('/register').post(userController.post);
//Authenticate
UserRouter.route('/authenticate').get();
//Profile
UserRouter.route('/profile').get();
// UserRouter is a middleware function
return UserRouter;
};
module.exports = userRoutes;
see express router part here : http://expressjs.com/en/guide/routing.html

How to create an database file in the mongoose and return back in the json format

Im reffering this video tutorial from this link "https://app.pluralsight.com/player?course=node-js-express-rest-web-services&author=jonathan-mills&name=node-js-express-rest-web-services-m6&clip=2&mode=live"....Here im returning the student in the json format...But dont know how to create it...So im getting an empty one...Is there any way to create that in the mongoose...Any1 please check my code and say
app.js
var express = require('express'),
mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/studentAPI');
var studentinfo = require('./models/studentModel');
var app = express();
var PORT = process.env.PORT || 3000;
var tutorRouter =express.Router();
tutorRouter.route('/student')
.get(function(req,res){
studentinfo.find(function(err,student){
if(err)
res.status(500).send(err);
else
res.json(student);
});
});
app.use('/api',tutorRouter)
app.get('/',function(req,res){
res.send('Welcome to my API')
});
app.listen(PORT,function(){
console.log('Running on port: ' + PORT);
});
studentModel.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema();
var studentModel = new mongoose.Schema({
name:{
type: String
},
parentname:{
type: String
}
});
module.exports = mongoose.model('studentinfo',studentModel);

get data from mLab using modules

I trying to get data from mLab.
In function /getAll I am trying to get all the JSONs I entered in a collection.
I understood that to get all of the details I need to use the function find.
When I run it (node app.js) - I can see it waiting but nothing happens and I don't get anything on localhost:3000/getAll (it's not loading)
here is app.js
var express = require('express');
var app = express();
var stud = require('./grades');
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://<myuser>:<mypass>#<dataaddress>');
var port = process.env.PORT || 3000;
mongoose.connection.once('open', function(){
stud(app);
mongoose.disconnect();
});
app.listen(port);
and this is gadres.js
var express = require('express');
var fs = require('fs');
var app = express();
var util = require('util');
var mongoose = require('mongoose');
var schema = mongoose.Schema;
var studSchema = new schema({
id : {type:Number, unique:true, required:true},
name : {type:String, required:true},
grade : Number,
course : {type:String},
year : Number
},{collection: 'details'});
var stud = mongoose.model('stud', studSchema);
module.exports = function (app) {
app.get('/getAll', function(req, res) { // if url in path is getAll
stud.find({}, function(err, user){
if(err) throw err;
console.log(user);
});
})
});

Categories