I have a new express.js application and I want to put my model in a different file using sequelize.
In my root dir I have a db.js that have this code
const Sequelize = require('sequelize');
// connect to MySql database
const db = new Sequelize('mysql://root:password#localhost:8889/myDB');
module.exports = db;
I'm exporting the db
Now in my root directory I have a models folder and inside the model folder I have a user.js file and in there I have this code.
const Sequelize = require('sequelize')
const db = require('../db')
const user = db.def('user', {
firstName: {
type: Sequelize.STRING
}
})
module.exports = user;
this give me this error.
db.def is not a function
I have merge the two files together it works, but it doesn't work i I break it in two separate files it doesn't.
It there's something I don't understand about export modules?
Related
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);
I'm having a really weird issue where Mongoose will not perform queries against collections outside of the Model definition file when NODE_ENV=production, even when connecting to localhost.
db/default.js
const mongoose = require('mongoose');
module.exports = {
connect(url) {
mongoose.connect(url);
}
};
app.js
const db = require('./db/default');
db.connect(config.get('mongoDB.uri'));
User.model.js
const mongoose = require('mongoose');
const schema = new mongoose.Schema({
// ...
});
const User = mongoose.model('User', schema);
module.exports = User;
test.js
// This file is required by a route
const User = require('./models/User.model');
User.find({})
.then(response => console.log(response))
.catch(err => console.log(err));
All of this works absolutely fine when NODE_ENV=dev, but as soon as NODE_ENV=production, the User.find({})... doesn't run. No errors, no success, it just doesn't run.
If I log the User = require('./models/User.model'), it is a Mongoose object.
If I run the User.find({})... code inside the User.model.js file whilst in production, that also works.
I am utterly befuddled as to why this does not work.
You can retrieve a Mongoose model like so:
let User = mongoose.model('User');
I am looking to do get an associative array of these models.
Is there some clever way of getting a list of models using object destructuring? Something like:
const {User, Employees, Managers} = mongoose.model('x');
My current solution is to do this:
/project
/models
index.js
where index.js looks like:
module.exports = {
User: require('./user'),
Employee: require('./employee'),
Manager: require('./manager'),
};
Where the user.js, employee.js and manager.js files just look like:
let mongoose = require('mongoose');
let Schema = mongoose.Schema;
let userSchema = new Schema({...});
module.exports = mongoose.model('User', userSchema, 'users');
Then I can do this:
const {User, Employees, Managers} = require('./models');
But I am looking for a better solution that requires no manual work if possible.
const models = {};
mongoose.modelNames().forEach(function(modelName){
models[modelName] = mongoose.model(modelName);
});
console.log(models);
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.
I have this basic structure ./api/controllers/authenticate.js and ./api/models/authenticate.js I want my controller to access the authenticate.js in the models folder as seen here.
controllers/authenticate.js
var app = require("express");
var router = app.Router();
var model = require("./api/models/authenticate.js");
router.get('/login',function(req,res){
res.send(model.authenticate());
});
module.exports = router;
models/authenticate.js
var authenticate = function() {
return "You should see this module";
}
module.exports = authenticate;
However I am getting a can not find the authenticate.js module in the models file. What am I missing?
controllers/authenticate.js
var app = require("express");
var router = app.Router();
var model = require("../models/authenticate.js");
router.get('/login',function(req,res){
res.send(model.authenticate());
});
module.exports = router;
var model = require("./api/models/authenticate.js"); is wrong as you are already in /api/controllers/ directory and you are trying to access the models directory so you have to come one step back by using ../ then entering into models. your case trying to access a directory inside the models directory inside the controller directory