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 );
});
Related
I'm building a pretty simple API to do a basic CRUD operations on a local mongo database. The code looks fine for me but somehow the CRUD operations results on a pending request which never ends.
Here the parts of the code:
spawn.model.js (Model corresponding to database collection)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SpawnSchema = Schema({
Name: {
type: String,
unique: false,
required: true
}
}, { timestamps: true });
module.exports = mongoose.model('spawns', SpawnSchema);
spawn.controller.js
var Spawn = require('../models/Spawn/spawn.model');
exports.getSpawns = function(req, res){
Spawn.find({}, function(spawns){
res.send(spawns);
});
}
Here the spawn.routes.js file:
var Spawns = require('../controllers/spawn.controller');
module.exports = function(app){
app.get('/list', Spawns.getSpawns);
}
And then finally the server.js file:
var express = require('express');
var bodyParser = require('body-parser');
var properties = require('./config/properties');
var db = require('./config/database');
var app = express();
//configure bodyparser
var bodyParserJSON = bodyParser.json();
var bodyParserURLEncoded = bodyParser.urlencoded({ extended: true });
// call the database connectivity function
db();
// configure app.use()
app.use(bodyParserJSON);
app.use(bodyParserURLEncoded);
// Routes
app.get('/', function(req, res){
res.json({ message: 'Spawns API' });
});
require('./app/routes/spawn.routes')(app);
// intialise server
app.listen(properties.PORT, () => {
console.log(`Server is running on ${properties.PORT} port.`);
})
The database file on ./config is the following:
var mongoose = require('mongoose');
var dbURL = require('./properties').DB;
mongoose.Promise = global.Promise;
module.exports = function(){
mongoose.connect(dbURL, { useNewUrlParser: true }, function(){
console.log('Successfully connected to database');
});
}
And the properties.js on /config is simply an object with the database URL and the port for the express server.
When I try to to a request through Postman to the URL: http://localhost:4000/list the request gets hanged and never resolves. What am I missing?
PD: SOLVED!
===========
I needed to update mongoose version on npm cause it was 3.x and needed to be 5.x in order to work well with the new methods.
Update your code little bit, Like this and check
spwanRoute.js
const express = require('express');
const router = express.Router();
const spawnCntr = require('./speanControllers');
router.get('/list', spawnCntr.getSpawns);
module.exports = router;
spwanUtils.js
const Spawns = require('../models/Spawn/spawn.dao');
const spawnUtils = {};
spawnUtils.getSpawns = (req, res) => {
try {
Spawns.get({}, (err, spawns) => {
if(err){
return res.status(400).json({ error: err });
}
return res.status(200).json({ spawns });
});
} catch (err) {
console.log(err);
return res.status(500).json({ error: 'INTERNAL_EROR' });
}
}
module.exports = spawnUtils;
I am trying to pass data to a MongoDB collection and it returns Cannot POST /courseweb/course/add
Before passing values through axios I tried postman (a google extension) to send data.
This is my server.js which is implemented with expressjs
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const Bundler = require("parcel-bundler");
const cors = require("cors");
const mongoose = require("mongoose");
const InstructorDB = require('./public/DBModels/InstructorDB');
const router = express.Router();
const bundler = new Bundler("./src/index.html");
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(bundler.middleware());
// app.use(express.static('./src'));
app.use("/courseweb", router);
mongoose.connect("mongodb://127.0.0.1:27017/courseweb", {
useNewUrlParser: true
});
const connection = mongoose.connection;
connection.once("open", () => {
console.log("Connected to MongoDB via 27017");
});
app.listen(3000, err => {
if (err) {
console.error(err);
process.exit(-1);
}
console.log("Application is running on port 3000");
});
app.get("/", function(req, res) {
res.sendFile("./dist/index.html");
});
router.route('/course/add').post((req, res) => {
let instructorDB = new InstructorDB(req.body);
instructorDB.save().then(bookDB => {
res.status(200).send(`${bookDB} Added`);
}).catch((err) => {
res.status(400).send({message: err});
});
});
router.route('/courses').get((req, res) => {
// name of the course database model here
InstructorDB.find().count(function(err, count){
res.status(200).send(count);
});
});
And this is my InstructorDB.js which is a schema model by mongoose
const mongoose= require('mongoose');
const Schema = mongoose.Schema;
let InstructorDB = new Schema({
firstName: String,
lastName: String,
designation: String,
faculty: String,
contactNumber: Number,
email: String,
password: String,
isEnabaled: Boolean,
courses: [{courseID: String}]
});
module.exports = mongoose.model('InstructorDB', InstructorDB, 'InstructorDB');
And this is a screenshot and the response I get when I pass the values through postman. I have set header as content-type and application/json too
Can anyone tell me where I have gone wrong?
Make sure you send the right data via your post request and change the verb to post :
app.post('/course/add', (req, res) => {
if(req.body == null){
return res.status(400).send({message: 'bad request'});
}
let instructorDB = new InstructorDB(req.body);
instructorDB.save((err ,doc ) => {
if(err){
res.status(400).send({message: err});
}
res.status(200).send(`Added`);
});
});
You don't need router if you're going to put it in the same file.
try this syntax instead:
app.post('/coureweb/course/add',((req, res) => {
let instructorDB = new InstructorDB(req.body);
instructorDB.save().then(bookDB => {
res.status(200).send(`${bookDB} Added`);
}).catch((err) => {
res.status(400).send({message: err});
});
}));
then take out
app.use("/courseweb")
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'));
});
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
I am trying to do a find with mongoose, but I get this
"TypeError: Query.find is not a function"
I have this model:
// file: ./models/request.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var dnSchema = new Schema({
customerId: String,
uuid: String,
get_data: String,
get_scores: String
});
dnSchema.index({ customerId: 1, time: -1 });
module.exports = mongoose.model('dN', dnSchema);
And I have this controller
var mongoose = require('mongoose');
var dn = mongoose.model('dn');
(...)
var getScores = exports.getScores = function(req, res) {
var Query = new dn();
console.log(Query)
Query.find({}, function(err, example) {
res.status(200).send(example)
});
}
And this index.js
var mongoose = require('mongoose');
mongoose.connect(config.url, function(err, res) {
if(err) {
logger.error('Error connecting to Database ' + process.pid);
throw err;
}
});
var models = require('./models/request')(app, mongoose);
var controllers = require('./controller/request');
var router = express.Router();
router.route('/get_scores')
.get(controllers.getScores);
app.use(router);
var httpServer = http.createServer(app);
httpServer.listen(config.port, function (){
controllers.logIn();
});
I am trying to do a simple .find, but I can do it.
I hope your help mates!!
Thanks you!!
Try to import the Schema in your controller and use that one.
var dn = require('path to schema file');
(...)
var getScores = exports.getScores = function(req, res) {
dn.find({}, function(err, example) {
res.status(200).send(example)
});
}