db is not a function error in NodeJS using MongoDB - node.js

I got this error in my application that is previously working
const usersCollection = require('../db').db().collection("users")
^
TypeError: require(...).db is not a function
at Object.<anonymous> (/Users/user/Desktop/sites/app/models/User.js:2:42)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/Users/user/Desktop/sites/app/controllers/userController.js:1:14)
db.js
const dotenv = require('dotenv')
dotenv.config()
const mongodb = require('mongodb')
mongodb.connect(process.env.CONNECTIONSTRING, {useNewUrlParser: true, useUnifiedTopology:
true}, function(err, client) {
module.exports = client
const app = require('./app')
app.listen(process.env.PORT)
})
.env file
CONNECTIONSTRING=mongodb+srv://user:password#sandbox-gk8wp.mongodb.net/db?
retryWrites=true&w=majority
PORT=3000
I have updated also my mongodb npm package from 3.3.3 to 3.4.1 but still the same error. What seems to be the problem?

You are trying to export something in the callback which may or may not be available when you import it as it is asynchronous method. Better way will be to create db.js like
const dotenv = require('dotenv')
dotenv.config()
const mongodb = require('mongodb')
function getMongoClient() {
return mongodb.connect(process.env.CONNECTIONSTRING, {useNewUrlParser: true, useUnifiedTopology: true});
}
module.exports = getMongoClient;
And when you want to use it
const getMongoClient = require('../db');
getMongoClient()
.then(client => client.db().collection("users"));
Hope this helps. You could also use async/await.

Related

Cannot read property 'connect' of undefined in env file

const dotenv = require('dotenv');
const { mongoose } = require('mongoose');
// const bodyParser = require('body-parser');
const app = express();
app.use(express.json());
const DB = `mongodb+srv://${process.env.MONGO_DB_USER}:${process.env.MONGO_DB_PASSWORD}#cluster0.70g8h.mongodb.net/${process.env.MONGO_DB_DATABASE}?retryWrites=true&w=majority`
mongoose.connect( DB ,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
})
.then( ()=>console.log('Connection Success ..'))
.catch( (err)=>console.log(' Not Connection Success'));
dotenv.config({path:'./config.env'});
app.get('/', (req, res,next) => {
res.status(200).json({
message:'Hello'
});
});
app.post('/data', (req, res,next) => {
res.status(200).json({
message: req.body
});
});
app.listen(process.env.PORT,()=>{
console.log(`Server is runing at the port : ${process.env.PORT}`);
})
Getting this error when using this code, I would like to know what is causing the error and any possible fixes. I am using atlas MongoDB
this is the output
D:\WebDevelopment.Ravi\Projects\mern_ecommerce\e-commerce-backend\src\index.server.js:9
mongoose.connect( DB ,
^
TypeError: Cannot read property 'connect' of undefined
at Object.<anonymous> (D:\WebDevelopment.Ravi\Projects\mern_ecommerce\e-commerce-backend\src\index.server.js:9:10)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
[nodemon] app crashed - waiting for file changes before starting..
Getting this error when using this code, I would like to know what is causing the error and any possible fixes. I am using atlas MongoDB
From ths docs Getting Started. It should be const mongoose = require('mongoose');
Try this, it should work:
const mongoose =require("mongoose");
require('dotenv').config();

`mongoose.connect()` fires error: first argument should be String, received

throw new MongooseError('The uri parameter to openUri() must be
a ' +
^
MongooseError: The uri parameter to openUri() must be a string,
got "undefined". Make sur
first parameter to mongoose.connect() or mongoose.createConnection() is a string.
at NativeConnection.Connection.openUri (C:\Users\niko\Desktop\opaa\node_modules\mongoose\nnection.js:694:11)
at _mongoose._promiseOrCallback.cb (C:\Users\niko\Desktop\opaa\node_modules\mongoose\lib\js:351:10)
at promiseOrCallback (C:\Users\niko\Desktop\opaa\node_modules\mongoose\lib\helpers\promislback.js:10:12)
at Mongoose._promiseOrCallback (C:\Users\niko\Desktop\opaa\node_modules\mongoose\lib\inde at
Mongoose.connect
(C:\Users\niko\Desktop\opaa\node_modules\mongoose\lib\index.js:350:20)
at Object. (C:\Users\niko\Desktop\opaa\app.js:9:10)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
const { response } = require('express');
const express = require('express');
const path = require('path');
const dotenv = require('dotenv')
const mongoose = require('mongoose');
dotenv.config();
mongoose.connect( process.env.DB_CONNECT, { useNewUrlParser: true }, () =>{
console.log("connected to db");
});
const route = require('./routers/routers');
const { connect } = require('./routers/routers');
const app = express();
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.set("views", "views")
app.set("view engine", "hbs")
app.use(express.static('public'));
app.use('/user', route);
app.listen(3000, () => console.log("Server Is Runing on localhost:3000"));
You may try to be sure you've passed the DB_CONNECT.
you may try DB_CONNECT=YOUR_DB_URI node index.js
also, you may check with console.log(process.env.DB_CONNECT) at the beginning of your script.
The error message tells that the mongoose.connect received URL is undefined. I suggest you instead process.env.DB_CONNECT try passing an URL to the DB for testing purpose see if that works.
The issue is with the process.env.DB_CONNECT is not setting up correctly, you might need to check dotenv configuration.

TypeError: connection.model is not a function in mongoose-auto-increment

I tried to connect mongodb. But I couldn't it. I thought [autoIncrement.initialize] is problem, but I couldn't solve the problem. This is my code.
const mongoose = require('mongoose');
const autoIncrement = require('mongoose-auto-increment');
require('dotenv').config();
mongoose.Promise = global.Promise;
const connect = mongoose.connect(process.env.MONGODB_URI);
autoIncrement.initialize(connect);
Here is error traceback:
/Users/loo/Projects/example-app/node_modules/mongoose-auto-increment/index.js:27
throw ex;
^
TypeError: connection.model is not a function
at Object.exports.initialize (/Users/loo/Projects/example-app/node_modules/mongoose-auto-increment/index.js:10:34)
at Object.<anonymous> (/Users/loo/Projects/example-app/app.js:8:15)
at Module._compile (internal/modules/cjs/loader.js:702:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
at Module.load (internal/modules/cjs/loader.js:612:32)
at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
at Function.Module._load (internal/modules/cjs/loader.js:543:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:744:10)
at startup (internal/bootstrap/node.js:238:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:572:3)
As You read example in this link
You would see this:
var connection = mongoose.createConnection("mongodb://localhost/myDatabase");
autoIncrement.initialize(connection);
In fact .connect and .createConnection are different things.
Due to documentation here which says:
Mongoose creates a default connection when you call
mongoose.connect().
You can access the default connection using
mongoose.connection.
that means mongoose.connect does not return connection and You can get that connection using mongoose.connection.
Solution:
mongoose.connect(process.env.MONGODB_URI, {useNewUrlParser: true})
.then(() => {
console.log('Connected to DB');
})
.catch(error => {
console.error('Connection to DB Failed');
console.error(error.message);
process.exit(-1);
});
autoIncrement.initialize(mongoose.connection);
or You can create a connection as here:
const connection = mongoose.createConnection(process.env.MONGODB_URI);
autoIncrement.initialize(connection);

Minimum Required Node Version for GraphQL?

I am trying to get a reference implementation of GraphQL.js working in a Node.js environment as a server. Note that I have limited experience with Node.js. Right now, I am using node v4.2.6, which is the latest package from Ubuntu for Ubuntu 16.04.
The official documentation says that this script should work:
var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');
// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
type Query {
hello: String
}
`);
// The root provides a resolver function for each API endpoint
var root = {
hello: () => {
return 'Hello world!';
},
};
var app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');
That fails with a syntax error:
server.js:3
var { buildSchema } = require('graphql');
^
SyntaxError: Unexpected token {
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:374:25)
at Object.Module._extensions..js (module.js:417:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:442:10)
at startup (node.js:136:18)
at node.js:966:3
The express-graphql project site shows a significantly different script, but one where I have to assemble a schema separately. The GraphQL.js project site has this script for assembling a schema:
import {
graphql,
GraphQLSchema,
GraphQLObjectType,
GraphQLString
} from 'graphql';
var schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: {
hello: {
type: GraphQLString,
resolve() {
return 'world';
}
}
}
})
});
That too fails with a syntax error:
server.js:1
(function (exports, require, module, __filename, __dirname) { import {
^^^^^^
SyntaxError: Unexpected reserved word
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:374:25)
at Object.Module._extensions..js (module.js:417:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:442:10)
at startup (node.js:136:18)
at node.js:966:3
I am guessing that perhaps v4.2.6 of Node.js is too old. Is that correct? If so, what is the minimum version of Node.js required to use GraphQL.js and express-graphql? And, if that's not my problem... any idea what is?
tThe prerequisites for that tutorial say:
Before getting started, you should have Node v6 installed [...]
Though to be fair it continues with:
[...] , although the examples should mostly work in previous versions of Node as well.
Node v4 doesn't support destructuring, which is the part it's choking on for you. You can check out node.green for a reference on what features are supported by what Node versions.
That too fails with a syntax error:
import|export aren't supported in any version of Node. You'd have to transpile that. Or you can just use Node's module system. For that it should look something like:
var graphqlModule = require("graphql");
var graphql = graphqlModule.graphql;
var GraphQLSchema = graphqlModule.GraphQLSchema;
// ...

mongoose returning Schema hasn't been registered for model

I have the following error on my express app which tells me that I haven't registered my schema but infact that I have already done that.
/home/work/dashboard/node_modules/mongoose/lib/index.js:333
throw new mongoose.Error.MissingSchemaError(name);
^
MissingSchemaError: Schema hasn't been registered for model "Devices".
Use mongoose.model(name, schema)
at Mongoose.model (/home/work/dashboard/node_modules/mongoose/lib/index.js:333:13)
at Object.<anonymous> (/home/work/dashboard/server/services/devices.js:6:28)
at Module._compile (module.js:435:26)
at normalLoader (/home/work/dashboard/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:199:5)
at Object.require.extensions.(anonymous function) [as .js] (/home/work/dashboard/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:216:7)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Module.require (module.js:366:17)
at require (module.js:385:17)
at Object.<anonymous> (/home/work/dashboard/server/routes/index.js:2:25)
at Module._compile (module.js:435:26)
at normalLoader (/home/work/dashboard/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:199:5)
at Object.require.extensions.(anonymous function) [as .js] (/home/work/dashboard/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:216:7)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Module.require (module.js:366:17)
at require (module.js:385:17)
This is what my model looks like
import mongoose from 'mongoose';
var Schema = mongoose.Schema;
var Devices = new Schema({
userName: {
type: String,
unique: true
},
userId: {
type: String,
unique: true
},
devices: [{
gatwayId: String,
type: String
}]
}, {
collection: 'devices'
});
Devices = mongoose.model('Devices', Devices);
export default Devices;
and here is the service that is supposed to call the model.
'use strict';
import mongoose from 'mongoose';
import _ from 'lodash';
var deviceModel = mongoose.model('Devices');
An finally this is how it looks like on the main index.js
import express from 'express';
import http from 'http';
import cors from 'cors';
import api from './routes';
import mongoose from 'mongoose';
import dotenv from 'dotenv';
import logger from 'morgan';
import bodyParser from 'body-parser';
import fs from 'fs';
import join from 'join';
dotenv.config();
var app = express();
app.server = http.createServer(app);
app.db = mongoose.createConnection(process.env.MONGO_URL);
app.db.on('error', console.error.bind(console, 'mongoose connection error: '));
app.db.once('open', function() {
console.log('connected to the mongoose database');
});
// Bootstrap models
fs.readdirSync(join(__dirname, 'models')).forEach(function (file) {
if (~file.indexOf('.js')) require(join(__dirname, 'models', file));
});
// 3rd party middleware
app.use(cors({
exposedHeaders: ['Link']
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(logger('dev'));
// api router
app.use('/api', api);
app.server.listen(process.env.PORT || 6000);
console.log(`Started on port ${app.server.address().port}`);
export default app;
You'll need to import your file where you define the model somewhere. So somewhere in your code do.
import Device from './path/to/your/model/file'

Resources