.post requires callback functions but got a [object Undefined] - node.js

I am trying to use routes but it's throwing an error.
its working without routes, so there must be some problem in routes,
Would you mind helping me?
index.js (routes folder)
module.exports = function(events){
var mongoose = require('mongoose');
var loadSchema = require('../schemas/index');
var functions={};
// save function
functions.saveEvent = function (req, res) {
//schema loading
new loadSchema({
name:req.body.organizer,
email:req.body.email,
address:req.body.address,
street:req.body.street,
price:req.body.price,
category:req.body.category,
otherInfo:req.body.otherInfo
}).save(function(error,data){
if(error)
res.json(error);
else
res.send("Event Saved");
});
};
return functions;
}
app.js
app.post('/addEvent',routes.saveEvent); // addEvent is the action of form
index.js (schemas folder)
var mongoose = require('mongoose');
module.exports = mongoose.model('user', {
name: Number,
email: String,
favoriteBook: String,
password: String,
confimrPassword: String
});
module.exports=mongoose.model('event',{
organizer:String,
email:String,
address:String,
street:String,
category:String,
price:String,
otherInfo:String
})
Error: .post requires callback functions but got a [object Undefined]

index.js (routes folder) exposes a function that returns your other middleware functions. If you want to have access to the middleware functions you need to invouke your exported function in index. JS:
Change
app.post('/addEvent',routes.saveEvent);
to
app.post('/addEvent',routes().saveEvent);

Related

is there a way to create a separate file for mongodb operation functions and use those functions in index file?

i have main code in index.js file with express server, and i want to create another file just to handle database CRUD operations. How can i do the following?
index.js
import functions from mongo.js
getUsers()
mongo.js
using MongoClient.connect to connect to db
function getUser(){
// get users from mongo db
}
You can achieve this creating helper function:
I will explain on example from my project:
First you need to create your helper function file
helper.js
module.exports = {
userAuthenticated: function(req, res, next){
if(req.isAuthenticated()){
return next();
}
res.redirect('/login')
}
};
As you can see I exported this function.
Then we are able to reach the code from it like this in other .js files:
other.js
const {userAuthenticated} = require('../../helpers/authentication.js');
router.all('/*', userAuthenticated, (req, res, next)=>{
req.app.locals.layout = 'admin';
next();
});
Do you use mongoose? I strictly recommend to use this lib instead of native connection driver.
You could achieve your goal by creating mongoose connection in a separate file, then import connection instance to the file with db schema. For example:
const mongoose = require("./mongo");
const Schema = mongoose.Schema;
const User = new Schema({
name: { type: String },
password: { type: String })
const UserModel = mongoose.model("User",User);
module.exports = {
model: UserModel,
getById: id => UserModel.find({_id:id})
}
And then just import those file in the place where you want to use it:
const UserModel = require("./User");
...
UserModel.getById("someid").then(handler);

Node.js API express web server MongoDB

I'm writing an Node.js REST API using express web server and mongoDB as DB server.
The project's directory tree is the following :
https://i.stack.imgur.com/LFWGt.png
When I try to access "/new/test" route, I'm getting the error "Cannot GET /new/test". By accessing this path it should create an new entry into the DB based on "firstname" URL parameter.
Routes.js :
'use strict';
module.exports = function(app) {
var americaine = require('../controllers/americaineController');
// Firstname Routes
app.route('/new/:firstname')
.post(americaine.new_firstname);
};
DB entry creation function is located on Controller.js :
'use strict';
var mongoose = require('mongoose'),
Firstname = mongoose.model('Firstname');
exports.new_firstname = function(req, res) {
var new_firstname = Firstname(req.params.firstname);
new_firstname.save(function(err, firstname) {
if (err)
res.send(err);
res.json(firstname);
});
};
Model.js :
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var FirstNameSchema = new Schema({
/*id: {
type: Number,
required: false
},*/
name: {
type: String,
required: true
}
});
module.exports = mongoose.model('Firstname', FirstNameSchema);
Do you guys have any ideas about my issue ? Thanks in advance.
Jérémy
change the method .post() to .get()
since you're actually doing a get request and not a post request.

Exporting a Mongoose connection that becomes available in an async callback?

I'm new to coding in Node.js and I've created a DB connection through mongoose, then exporting the database object into my main app.js file:
// db.js
var mongoose = require("mongoose");
var uri = /*The URL*/;
var db = mongoose.connect(uri, {
useMongoClient: true
});
exports.db = db;
Here I'm trying to use that DB connection to perform CRUD operations:
// app.js
var db = require('./db');
app.post('/', function (req, res) {
db.collection(/* … */); // throws error
});
The error is:
TypeError: db.collection is not a function
I think this is because that the call of connect in the db.js is asynchronous and the require in app.js is synchronous - so it'll be undefined when I execute db.collection?? How can Mongoose be used to avoid this error?
Goal: I want to be able to call db.collection.insertOne() within my app.js
I found a somewhat related topic but it doesn't use Mongoose, so I'm confused as to how to resolve this issue: How to export an object that only becomes available in an async callback?
Answering my own question:
It'll need a mongoose model in the app.js. So instead of doing db.collection in the main app.js, I ended up routing the CRUD operations to functions defined in the controller file.
//app.js
var app = express();
var router = express.Router();
app.use(router);
require("./Routes")(router);
router.get("/xxx", xxx.get);
Here are the routes:
//routes.js - takes care of routing URLs to the functions
var XXX = require('../xxx');
module.exports = function(router){
router.get('/XXX', XXX.get)
};
Here is the actual function:
//xxx.js - functions defined here
exports.get = function (req, res) {
XXX.getAll(req.body, function(err, result){
if (!err) {
return res.send(result); // Posting all the XXX
} else {
return res.send(err); // 500 error
}
});
};

require is not defined in angular

I am using angularjs where i have created a js file(loginCtrl.js) and i have inclused a controller.
I have defined my db connection and schema in another file(server.js) and i want to include that file in my js.
My loginCtrl.js looks like:
test.controller('loginCtrl', function($scope, loginService){
$scope.login = function(user)
{
console.log('inside function 1');
var user = require('./server.js')
console.log('inside function');
loginService.login(user);
}
});
and my server.js files looks like:
var express = require('express');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/userregistration');
var userSchema = {
username: String,
firstname:String,
lastname: String,
email: String,
password: String
}
var User = mongoose.model('User', userSchema, 'user');
When i run the code, it gives the error like:
ReferenceError: require is not defined
It is printing the console.log defined above.
require() is a NodeJS function, your angular controller will be executed in the browser, which doesn't have that built-in function. If you want to replicate that behavior client-side, you should look at RequireJS

Mongoose Find not working

This is my first time writing a MVC app in Node/Express/Mongoose so I could really use some help. My .find() command just doesn't find anything! :(
Structure is that I have a an /app folder in the root. /app folder contains /models (schemas), /controllers and /views in it. And I have app.js outside in the root.
Somewhere in app.js:
// all necessary config/setup stuff..
var mongoose = require('mongoose');
mongoose.connect(config.db);
var app = express();
require('./config/routes')(app)
In my routes.js file:
var skills = require('../app/controllers/skills');
app.get('/', skills.showall);
My controller skills.js contains:
var Skill = require('../models/skill');
exports.showall = function(req, res) {
Skill.find({}, function(err, docs){
if (!err) {
res.render('index', {title: 'Skilldom', skills: docs});
}
else {
throw err;
}
});
}
Finally my Model skill.js contains:
var mongoose = require('mongoose');
//Skill schema definition
var skillSchema = new mongoose.Schema({
name: String,
length: String,
});
var Skill = mongoose.model('Skill', skillSchema);
module.exports = Skill;
My index view renders, so I see the content from my index.jade template, but for some reason the find command in the model is not fetching anything. I can confirm that my database (in MongoHQ) has real data.
Any thoughts?
Change your Skill.js for this
var mongoose = require('mongoose');
mongoose.set('debug', true);
//Skill schema definition
var skillSchema = new mongoose.Schema({
name: String,
length: String,
});
var Skill = mongoose.model('Skill', skillSchema);
module.exports = Skill;
After that, you can see at the console if mongoose is doing your queries.
I was in the same situation as you describe and it turns out I didn't understand the magic of mongoose collection naming, in your code it will try to load the "skills" and if that's not what it's named in your mongo nothing will be returned. Should really toss a "so such collection" error instead imho.
This below method gives an alternate name for your collection
var skillSchema = new mongoose.Schema({
name: String,
length: String,
},{collection : 'Skill'});
or
var Skill = mongoose.model('Skill', skillSchema,''Skill);

Resources