Get (associative) array of Mongoose models - node.js

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);

Related

Get existing document from MongoDB with Mongoose

I have an existing document on MongoDB atlas that I need to get in its entirety. When I try my current code I get a socket timeout, i.e. it keeps buffering.
There is only one document in my collection.
My theory is that the error is in my Mongoose Schema, but I don't know what to put there since I don't want any "filters", I want everything.
The name of the collection in Atlas is Playstation and the id of the document I want to get is: 5f5e2d281386efc27bb3ce45
const express = require('express')
const router = express.Router()
const Playstation = require('../models/playstation')
//Getting All
router.get('/', async (req, res) => {
try {
const playstations = await Playstation.findById("5f5e2d281386efc27bb3ce45")
res.json(playstations)
} catch (err) {
res.status(500).json({ message: err.message })
}
})
module.exports = router;
My schema & model:
const mongoose = require('mongoose')
const playstationSchema = new mongoose.Schema({
})
module.exports = mongoose.model('Playstation', playstationSchema)
I believe the problem is your mongoose schema. What you want is a schemaless collection, since you dont want to define the schema, and you want everything in the document, you can define the collection as schema-less, with strict:false option in your mongoose schema;
Try this:
const mongoose = require('mongoose')
const playstationSchema = new mongoose.Schema({
},{ strict : false })
module.exports = mongoose.model('Playstation', playstationSchema);
You can read more about this option on Mongoose Documentation

Mongoose MongoDB in Production

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.

how to put a model in a different file in Sequelize

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?

Understanding mongoose connections in express.js

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.

modifying results in post find mongoose hook

I am trying to find a way to modify the query results of mongoose.
Below is the self contained model with the post hook
'use strict';
// load the things we need
var mongoose = require('mongoose');
var invoice_db = mongoose.createConnection(config.mongo.url + '/invoiceDB'); //connect to buyer DB
var path = require('path');
// define the schema for our invoice details model
var invoicedetailSchema = new Schema({
//SCHEMA INFO
});
invoicedetailSchema.post('find', function(results){
console.log('POST FIRED')
results = results.filter(function(doc){
return doc.tags.length;
})
})
var InvoiceModel = invoice_db.model('InvoiceDetail', invoicedetailSchema);
// create the model for seller and expose it to our app
promise.promisifyAll(InvoiceModel);
promise.promisifyAll(InvoiceModel.prototype);
module.exports = InvoiceModel;
The find query is working fine and the post is firing but the results are not filtered per the post hook.
How do i go about editing the results before the results are returned.

Resources