Mongoose: cyclic dependency detected - express

I've got an Express/Mongoose app that keeps throwing "cyclic dependency detected" errors at me. I've localized the problem to one of these files.
app.js
var express = require('express');
var mongoose = require('mongoose');
mongoose.connect('mongodb+srv://username:MY.PASSWORD#cluster0-6vlss.mongodb.net/test?retryWrites=true');
require('./models/Users');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
routes/users.js
var mongoose = require('mongoose');
var express = require('express');
var router = express.Router();
var User = mongoose.model('User');
router.route('/user/:id')
.get((req, res, next) => {
User.findById(req.params.id, (err, user) => {
if (err) return next(err);
res.json(user);
});
});
models/Users.js
var mongoose = require('mongoose');
var UserSchema = mongoose.Schema({
_id: String,
username: {type: String, unique: true},
hash: String,
salt: String,
chats: Array
});
var User = mongoose.model('User', UserSchema);
module.exports = User;
Hopefully I condensed my code well enough. Could somebody point to my screw-up?

Got it. In app.js, dbconfig is an object that stores the database URI string. I called "dbconfig" directly instead of "dbconfig.url". Everything's good now.

Related

expressJS is preventing me to post a resource

I'm trying to build a mini app in express, the "database" I'm using is a local array object file, I can retrieve resources from this "database" but for some reason I'm not able to post (push) a new object to this object array. This is how the code looks like:
server.js:
const express = require('express');
const app = express();
const userRouter = require('./routes/user.js');
const port = process.env.PORT || 3000;
app.use(express.json());
app.use(express.text());
app.use('/user', userRouter);
app.listen(3000, () => console.log(`listening at ${port}`));
user.js:
const express = require('express');
const BBDD = require('./BBDD.js');
const userRouter = express.Router();
userRouter.get('/:guid', (req, res, next) => {
const { guid } = req.params;
const user = BBDD.find(user => user.guid === guid);
if (!user) res.status(404).send()
res.send(user);
next();
});
userRouter.post('/', (req, res, next) => {
let user = {};
user.name = req.body.name;
user.id = req.body.id;
BBDD.push(user);
next();
});
module.exports = userRouter;
And this is my local "database" file I want to perform logical CRUD operations:
BBDD.js
const BBDD = [{
index: 0,
guid: "1",
name: "Goku"
},
{
index: 1,
guid: "2",
name: "Vegeta"
},
];
module.exports = BBDD;
this is how I try to post a new resource, and this is the error I get:
It seems to be in order, but it won't work and can't find the bug.
Remove the next and send a response .express is having trouble finding the next matching handler because there is none

how to sensitize req.body object data in express

I want to remove all malicious data input from my express api requests?
how I sensitize data
"use strict";
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const bodyParser = require("body-parser");
const mongoose = require('mongoose');
require('dotenv').config();
var util= require('util');
var cors = require('cors');
I am using this all package in above code
You can use lodash to do that sanitize process, in the following way.
const _ = require('lodash');
function sanitize(body, values) {
return _.pick(req.body, values);
}
console.log(sanitize(req.body, ['name', 'email', 'password']));
If you are using express you can the following middleware as follow:
const validatorFunc = (values) => {
return (req,res,next) => {
const data = _.pick(req.body, values);
req.body = data;
next();
}
}
please refer to sanitize npm package for your request object
Link: https://www.npmjs.com/package/sanitize

connect-history-api-fallback get cannot access

During setup of nodejs(as backend, port: 3333), and vuejs(frontend, port: 8080) environment, I was unable to access 'GET /article'. Also, when I remove connect-history-api-fallback, all I can see is json formatted database data.
How can I fix this?
Below is the code for app.js:
var express = require('express');
var app = express();
var history = require('connect-history-api-fallback');
app.use(history({
index: '/index.html',
verbose: true
}));
app.use(express.static(path.join(__dirname, 'public')));
// app.use(bodyParser.json());
var IndexRouter = require('./routes/index');
var ArticleRouter = require('./routes/article');
app.use('/', IndexRouter);
app.use('/article', ArticleRouter);
Below is the code for routes/article.js:
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
router.get('/', function (req, res) {
console.log('article get 접근하였습니다.');
pool.getConnection(function (err, connection) {
if (err) {
throw error;
}
const sqlQuery = 'SELECT * from board_article';
connection.query(sqlQuery, function (err, rows) {
if (err) {
connection.release();
throw error;
} else {
res.json(rows);
connection.release();
}
});
});
});

Node express. Routes db.get and find method

Here is my routes/users.js file:
var express = require('express');
var router = express.Router();
/*
* GET userlist.
*/
router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('userlist');
collection.find({},{},function(e,docs){
res.json(docs);
});
});
module.exports = router;
In this code, what is the req object? And when we call req.db... that's made available to us via this right in app.js:
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest2');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
app.use(function(req,res,next){
req.db = db;
next();
});
What is the app.use exactly doing here?

Constructing document yields semi-empty result

After executing Customer.create({customerName: 'John'}), the following document is created without error and without the 'customerName' node.
Can anyone tell me why this seemingly simple document creation call yields a semi-blank document? The document in the response from Mongoose is the same as it is in the database itself.
I can't tell if I'm using Mongoose incorrectly or Express incorrectly. Thanks in advance for your help.
{ __v: 0, _id: 5452dc48d687bad849d70816 }
routes/customer.js
var mongoose = require( 'mongoose' );
var Customer = mongoose.model( 'Customer');
exports.create = function(req, res) {
Customer.create({
customerName: 'John'
}, function(err, customer) {
if (err) return err;
console.log('Customer created', customer);
res.send(customer);
});
}
schema/customer.js
var mongoose = require('mongoose');
var customerSchema = new mongoose.Schema({
customerName: {
type: String,
required: false
}
});
db.js
var mongoose = require( 'mongoose' );
var dbURI = 'mongodb://localhost/CustomerDatabase';
mongoose.connect(dbURI);
var customerSchema = require( '../schema/customer.js' );
var Customer = mongoose.model( 'Customer', customerSchema);
routes.js
function SetupRoutes(app, PATH) {
var db = require('../model/db.js')
var customer = require( '../routes/customer.js' );
app.post('/Customer', customer.create);
}
module.exports.SetupRoutes = SetupRoutes;
You need to export customerSchema from customer.js so that when db.js requires that file, its value is the exported schema:
var mongoose = require('mongoose');
var customerSchema = new mongoose.Schema({
customerName: {
type: String,
required: false
}
});
module.exports = customerSchema;
However, the more typical pattern is to create the model in customer.js and then export that:
var mongoose = require('mongoose');
var customerSchema = new mongoose.Schema({
customerName: {
type: String,
required: false
}
});
module.exports = mongoose.model('Customer', customerSchema);