This question already has answers here:
Reference error on node.js while include file
(2 answers)
Closed 6 years ago.
I'm writting my first nodejs app, and i'm getting an error when i move a piece of code to an external js file. the code i'm trying to move is a mongodb schema declaration:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//--------------------users ------------
var usersSchema = new Schema({
email: String,
name: String,
phoneNumber: String,
BirthDate: Date,
loginpwd:String
});
var UserModel = mongoose.model('users', usersSchema);
I'm using filesystem module to load the external file:
fs.readdirSync(__dirname+'/models').forEach(function(filename){
if (~filename.indexOf('.js'))
require(__dirname+'/models/'+ filename);
console.log(filename+" added");
});
the following block does not work well when I separate the code, throwing an "undefined UserModel" error:
var userData = new UserModel({email : req.body.edtEmail,
name: req.body.edtName,
phoneNumber: req.body.edtPhoneNumber,
BirthDate: req.body.edtBirthDate,
loginpwd: req.body.edtSenha});
// save user data to database
userData.save(function(err, record){
if(err) throw err;
// session setting
req.session.userEmail = req.body.edtEmail;
req.session.name = req.body.edtName;
req.session.phoneNumber = req.body.edtPhoneNumber;
req.session.birthDate = req.body.edtBirthDate;
req.session.userId = record._id;
res.redirect('/dashboard');
});
the following code works well in both inline code or "in file" code:
app.get('/users/json', function(req, res){
mongoose.model('users').find(function(err, users){
res.send(users);
});
});
Am I doing something wrong when load external file ? or missing something ?
There is a build in system in nodeJs to load files.
I am not really sure what you want to do but in nodejs you would do something like this
//Lets say this file is called UserModel.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//-------------------- rest of you code ------------
var UserModel = mongoose.model('users', usersSchema);
module.exports = UserModel; //this is important
Than in a another file you could just load this
var UserModel = require('UserModel');
var bob = new UserModel({ ....
so you can work with your UserModel. Read maybe the docs about require
Also can use like:
in your schema file: (say directory "models/userModel.js")
...
mongoose.model('UserModel', usersSchema);
in controller or other file where you want to use: (say directory "controller/userController.js")
require('../models/userModel');// load user model
var mongoose = require('mongoose'),
UserModel = mongoose.model('UserModel'),
var userData = new UserModel({email : req.body.edtEmail, //rest of code...});
userData.save(function(err, record){ //rest of code ...
and can use for route like: (follow like as controller)
app.get('/users/json', function(req, res){
UserModel.find(function(err, users){
res.send(users);
});
});
Related
I have created a mongoose model in a file User.js:
var mongoose = require('mongoose');
exports.GetUser=function(conn){
var UserSchema = mongoose.Schema({
username: String,
age: Number
},{collection:"User",versionKey: false});
var usermodal = conn.modal("User",UserSchema);
return usermodal;
}
I am importing and using it in test.js file like this:
var user = require('./User.js');
var mongoose = require('mongoose');
var conn = mongoose.createConnection(\\connection string and other config here);
var userModal = user.GetUser(conn);
userModal.find({},(err, result)=>{
console.log(result); //prints undefined
});
The result comes undefined here. When I moved the model inside test.js, it started working and fetched data from the collection correctly. I cannot find what is the issue here. There are other models as well in User.js which I am exporting and using in the same way but they are also not working.
Please help me to find the issue and correct it. Thanks!
I have added a method to my mongoose scheme. When I create an instance, I can call that object but when I query for that object and try to call the same method, it returns exception.
User.js file:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: String
surname: String
});
userSchema.methods.print = function() {
console.log(this.name, this.surname);
};
module.exports = mongoose.model('User', userSchema);
The following code works as expected:
const user = new User({});
user.print();
But when I query mongodb and try to call print on the method it returns exception:
User.findById(id, function(err,user){
// print is not a function
user.print();
});
I can't see where I'm making mistake,
And suggestions ?
Thanks.
It is because you haven't created an object of User.
Change module.exports = mongoose.model('User', userSchema); to let User = module.exports = mongoose.model('User', userSchema); in the User.js file and create an object of User before calling the print method, like:
let User = require('<path>/User.js'); where you need to update path with the actual path of the file.
I'm encoutering an error when using a Mongoose Model in my program.
I've did that in the beginning of my code :
var Schema = mongoose.Schema;
mongoose.connect('xxxxx');
I used a first schema called userSchema to connect/sign up a user.
I've this code, which should do a random on the field Bonus of my DB. But when I go to the randTest page, I have this error. How can I fix it ?
app.get('/randTest', function(req,res)
{
var bonusSchema = new Schema({
bonus : [String]
});
var bonusModel = mongoose.model('Plateau', bonusSchema);
var query = bonusModel.find(null);
query.exec(function (err, allBonus){
if(err) { throw err;}
var rand = Math.floor((Math.random() *allBonus.length));
var result = allBonus[rand-1];
});
res.render('randTest', {result: result});
});
In my Jade file I've just :
extends layout
block content
script.
alert({#result});
Move the bonusModel definition outside of app.get so that it's only called once:
var bonusSchema = new Schema({
bonus : [String]
});
var bonusModel = mongoose.model('Plateau', bonusSchema);
app.get('/randTest', function(req,res)
{
var query = bonusModel.find(null);
...
});
What is the best way to require a mongoose Schema in nodejs?
Originally I had these inside the app.js file but that is getting a bit large and unwieldy with more models.
Now I want to move them into a models folder and use Model = require('./models/model') to import them into app.js
How do I get it such that Model is populated with the actual model?
(exports = mongoose.model(...) fails and gives me a blank object; exports.model = mongoose.model(...) requires me to do Model.model to access it -- neither of these are the desired behavior)
===
Edit1
So basically I have taken
var mongoose = require('mongoose');
var Schema = mongoose.Schema, ObjectId = Schema.ObjectId;
var UserSchema = new Schema({
username: String,
password: String,
first_name: String,
last_name: String,
email: String
});
User = mongoose.model('User', UserSchema);
and put it into ./models/user.js
How do I get it such that its the equivalent of having this in the app.js?
In your app.js server file, include the model.js file like this:
var Model = require('./models/model'); //whatever you want to call it
You can then instantiate it in your server file like this:
//Initiate the Business API endpoints
var model = new Model(mq, siteConf);
model.getUser(id, function() {
// handle result
});
----
Then in your file you place in models folder named model.js (or whatever you want) you can set it up like this:
var mongoose = require('mongoose');
//MongoDB schemas
var Schema = mongoose.Schema;
var User = new Schema({
username: String,
password: String,
first_name: String,
last_name: String,
email: String
});
var UserModel = mongoose.model('User', User);
// your other objects defined ...
module.exports = function(mq, siteConf) {
//MongoDB
mongoose.connect(siteConf.mongoDbUrl);
// ------------------------
// READ API
// ------------------------
// Returns a user by ID
function getUser(id, found) {
console.log("find user by id: " + id);
UserModel.findById(id, found);
}
// Returns one user matching the given criteria
// mainly used to match against email/login during login
function getUserByCriteria(criteria, found) {
console.log("find user by criteria: " + JSON.stringify(criteria));
UserModel.findOne(criteria, found);
}
// more functions for your app ...
return {
'getUser': getUser,
'getUserByCriteria': getUserByCriteria
};
};
Windows 7 x64, node.js, mongoose from npm.
var sys = require('util');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:28960/test_mongoose');
var Schema = mongoose.Schema;
//Model
var UserSchema = new Schema({
username : String,
uid : String,
messaged_on : Date
});
mongoose.model('User', UserSchema);
var User = mongoose.model('User');
// create a new user
var user = new User({
uid : '54321',
username : 'Bob',
messaged_on : Date.now()
});
user.save( function (err) {
if (err)
return;
console.log('Saved');
User.find().all(function(user) {
console.log('beep');
});
});
Connection to mongod accepted, database 'test_mongoose' created.
Console print 'Saved', but 'beep' not.
I am newbie in mongoose, but, what is a prolem? Why do User.find().add() not call function back (user)?
Sorry for my bad english.
Maybe is it normal?
You should be calling User.find(... instead of User.find().all(.... The all method invokes the $all operator which is only used when matching arrays.