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
Related
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.
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);
I am learning express.js using the following project:
https://github.com/scotch-io/easy-node-authentication/tree/linking
In server.js I can see and understand the following initiates a connection to the database using the url from database.js:
var mongoose = require('mongoose');
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
/app/models/user.js contains the following:
var mongoose = require('mongoose');
var userSchema = mongoose.Schema({
local : {
email : String,
password : String,
},
...
}
module.exports = mongoose.model('User', userSchema);
Finally /config/passport.js contains:
var User = require('../app/models/user');
I can see how passport.js obtabs the model from user.js however I am failing to understand how user.js is aware of the connection setup in server.js as the initiated object "mongoose" is not exported?
What am I missing?
as you can see in this file index.js at the last line
var mongoose = module.exports = exports = new Mongoose;
this mean, Mongoosee will export only one instance (singleton) to handler database operations. because you first create connection in your server.js file, after that, any included/require model will have connection to your db server. all app will work on single object.
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);
I'm trying to add in my first plugin - mongoose-text-search.
https://npmjs.org/package/mongoose-text-search
I'm getting the error: How to Error: text search not enabled that I can't figure out.
I have my schema in seperate file where it gets compiled into a model that I export. (Works fine.)
blogSchema.js
var mongoose = require('mongoose');
var textSearch = require('mongoose-text-search');
var blogSchema = new mongoose.Schema({
title: String,
author: String,
}],
});
// give our schema text search capabilities
blogSchema.plugin(textSearch);
var Blog = mongoose.model('Blog', blogSchema);
exports.Blog = Blog;
This is relevant code for the server side. When the client sends a request to /search/,
the socket hangs up - Got error: socket hang up and on the server side I get the
How to Error: text search not enabled message.
server.js
var express = require('express')
, mongoose = require('mongoose')
, textSearch = require('mongoose-text-search');
var search_options = {
project: 'title -_id'
};
app.get('/search', function (req, res) {
console.log("inside text search");
Reading.textSearch('writing', search_options, function (err, output) {
if (err) throw err;
console.log(output);
});
});
Thanks.
You need to enable text search on the MongoDB server as described here as it's disabled by default.