No data is fetched while using mongoshell, it is working fine
server.js file
const express = require('express')
const app = express()
const cors = require('cors')
const mongoose = require('mongoose')
const topicRoute = require('./routes/topicRoute')
app.use(cors())
app.use(express.json())
const dbUri = "mongodb+srv://rohan:password#db_name.qg229.mongodb.net/db_name"
mongoose.connect(dbUri)
app.use("/",topicRoute)
app.listen(3001,function(){
console.log("Server started")
})
routes/topicRoute.js file, no error is catched here & object Object is returned
const express = require('express')
const router = express.Router()
const Topic = require('../models/topicModel')
router.route("/topics").get((req,res)=>{
Topic.find().then(fetchedTopics => res.json(fetchedTopics))
})
module.exports = router
models/topicModel.js file
const mongoose = require('mongoose')
const topicSchema = {
topic_id: String,
topic_name: String,
topic_description: String,
}
const Topic = mongoose.model('topics',topicSchema)
module.exports = Topic
Try with this code for database connection
// database connection
const { MongoClient, Collection } = require('mongodb');
const url = 'mongodb://localhost:27017' const database = 'ecom' // database name define here const collectionName = 'reviews'; //database collection define here const client = new MongoClient(url);
async function getData(){
let result =await client.connect();
let db = result.db(database)
let collection = db.collection(collectionName)
let response = await collection.find({}).toArray()
console.log(response); }
getData();
Related
I'm new to nodejs along with mongoDB, can anyone please help me to solve this issue. i used to multer, multer-gridfs-storage, gridfs-stream for uploading file and images.
But i'm getting this TypeError: mongodb_1.ObjectID is not a constructor in resolve() inside the promise in GridFsStorage. i have shared the code below.
const express = require('express');
const app = express();
require('dotenv').config()
const PORT = process.env.PORT;
const morgan = require('morgan');
const multer = require('multer');
const {GridFsStorage} = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const methodOverride = require('method-override');
const mongoose = require('mongoose');
const path = require('path');
const crypto = require('crypto');
const MongoURI = "atlas url";
app.use(methodOverride('_method'));
app.use(express.json())
app.use(morgan(':method :status :url'));
const connectDB = mongoose.createConnection(MongoURI,{useUnifiedTopology:true,useFindAndModify:false, useNewUrlParser:true,useCreateIndex: true})
let gfs;
connectDB.once('open',()=>{
console.log("dbConnected....")
gfs = Grid(connectDB.db,mongoose.mongo)
gfs.collection('uploads');
})
const storage = new GridFsStorage({
url:MongoURI,
file:(req,file)=>{
return new Promise((resolve, reject)=>{
crypto.randomBytes(16,(err,buf)=>{
console.log("buf",buf)
if(err){
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
console.log("filename",filename)
const fileInfo = {
filename:filename,
bucketName:'uploads'
};
resolve(fileInfo)
})
})
}
})
app.listen(PORT,()=>{
console.log(`port connected....${PORT}`)
})
const upload = multer({storage:storage})
app.post('/uploadfile',upload.single('file'),async(req,res)=>{
res.json({
file:req.file
})
})
My solution is to change the mongodb_1.ObjectID() inside its node module's gridfs.js file into mongodb_1.ObjectI"d"() and everything works. I guess the author is writing for the old version of mongodb, but in my case it's the newer version so "d" should be lowercase.
Update:
Someone just post an issue to the author's github, you can follow this page for official solutions.
You must call mongodb.ObjectId and not ObjectID, and then you can have a const with that name. But with ObjectId everything will work.
Keep on coding.
Visit https://github.com/devconcept/multer-gridfs-storage/issues/352#issue-946945336 Changing the method name from ObjectID() to ObjectId() of mongodb_1 class worked for me, looks like a compatibility issue in gridfs.js file in node_modules.
I have been getting a problem when I want to module.export the pool variable to use it in other files. I have this program in src\db\index.js:
const {Pool} = require('pg');
const express = require('express');
//Initialize
const path = require('path');
const app = express();
const fetch = require('fetch');
const PORT = process.env.PORT || 5000;
//Global Variables
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl:true
});
//Setting
app.use(express.static(path.join(__dirname, 'public')));
//Routes
app.use(require('../Routes/logIn'));
app.use(require('../Routes/singIn'));
app.use(require('../Routes/forgotPass.js'));
app.listen(PORT, () => console.log(`Listening on ${PORT}`));
module.exports = pool;
And then I want to require the const pool in this file src\Routes\LogIn.js:
const express = require('express');
const pool = require('../db');
const router = express.Router();
router.get('/usuario/:user', function (req, res) {
//console.log("GET usuario");
var user = req.params.user;
pool.query(
`select * from users where email = '${user}' limit 1`,
function (error, resq, fields) {
if (error) {
console.log(error);
} else {
console.log(user);
res.send(resq.rows);
}
}
);
});
module.exports = router;
But when I run the index.js and go to the route ulr/usuario/:user, in the logs I see that the program has an error that says "pool.query is not a function". I want to know how i could export the const pool to use it in other files.
You can use
module.exports = {
query: (text, params) => pool.query(text, params),
}
Use express-promise-router
const Router = require('express-promise-router')
const db = require('../db')
const router = new Router()
Use
await db.query(`
SELECT * from local
`)
instead of pool.query in your router.get or router.post
The above should solve your issue - You can check the same reference here
https://node-postgres.com/guides/async-express
How do I set my database and collection using mongoose ? I am trying to connect to a mongodb atlas database using mongoose. My database is called "test_db" and collection name is "users" where would I specify that information ?
This is my shema (data.js):
// /backend/data.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// this will be our data base's data structure
const DataSchema = new Schema(
{
_id: Number,
name: String,
password: String
}
);
// export the new Schema so we could modify it using Node.js
module.exports = mongoose.model("users", DataSchema);
and this is server.js:
const mongoose = require('mongoose');
const express = require('express');
var cors = require('cors');
const bodyParser = require('body-parser');
const logger = require('morgan');
const Data = require('./data');
const API_PORT = 3001;
const app = express();
app.use(cors());
const router = express.Router();
// this is our MongoDB database
const dbRoute = 'mongodb+srv://<user>:<password>#cluster0-bmihj.mongodb.net/test?retryWrites=true&w=majority';
;
// connects our back end code with the database
const conn = mongoose.connect(dbRoute, { useNewUrlParser: true });
//let db = mongoose.connection;
const db = conn.db('test_db');
var MyModel = mongoose.model('Test', new Schema({ name: String }));
db.once('open', () => console.log('connected to the database'));
// checks if connection with the database is successful
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
// this is our get method
// this method fetches all available data in our database
router.get('/getData', (req, res) => {
Data.find((err, data) => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true, data: data });
});
});
Through this line, you are connected to MongoDB:
const conn = mongoose.connect(dbRoute, { useNewUrlParser: true })
Consider:
dbRoute = mongodb://DB-username:DBpassword#ds245901.mlab.com:44422/Database-Name";
Here is your data information
DB-username = Your database user name
DBpassword = Your database password
Database-Name = Your database name (which database you want to use)
Therefore, no need to connect to your desired database like this:
const db = conn.db('test_db');
We are having a simple json-server setup, loading it as a module.
However, when making a POST/PUT request, the data is not being injected into the db.json.
const jsonServer = require("json-server");
const source = require("./db.json");
const repl = require("replify");
const bodyParser = require("body-parser");
const paginationMiddleware = require("./middlewares/pagination");
const filterByAccessRightFor = require("./middlewares/filterByAccessRightFor");
const searchMiddleware = require("./middlewares/search");
const delayMiddleware = require("./middlewares/delay");
const createdAt = require("./middlewares/created_at");
const daterange = require("./middlewares/daterange");
const absence = require("./middlewares/absence");
const bankAccount = require("./middlewares/bankAccount");
const sort = require("./middlewares/sort");
const fileUpload = require("express-fileupload");
const withUser = require("./responseEnhancers/withUser");
const withAbsenceType = require("./responseEnhancers/withAbsenceType");
const withIndexData = require("./responseEnhancers/withIndexData");
const withNationalStateHolidayOverride = require("./responseEnhancers/withNationalStateHolidayOverride");
const withRoleRestrictions = require("./responseEnhancers/withRoleRestrictions");
const compose = require("lodash/fp/compose");
const initSickImagesEndpoint = require("./features/sicks/images/initEndpoint");
const initLoginEndpoint = require("./features/login/initEndpoint");
const path = require("path");
const express = require("express");
const createCalendarEntry = require("./_helpers/createCalendarEntry");
process.on("createCalendarEntry", createCalendarEntry);
const server = jsonServer.create();
const defaultMiddlewares = jsonServer.defaults({
static: path.join(path.resolve(process.cwd()), "server", "files")
});
const router = jsonServer.router(source, {
foreignKeySuffix: "_id"
});
router.render = (req, res) => {
res = compose(
withIndexData(req),
withUser,
withAbsenceType,
withNationalStateHolidayOverride(req),
withRoleRestrictions(req, db)
)(res);
res.jsonp(res.locals.data);
};
const db = router.db;
if (process.env.NODE_ENV === "production")
server.use(express.static(path.join(__dirname, "../build")));
server
.use(
jsonServer.rewriter({
"/de/*": "/$1"
})
)
.use(bodyParser.json())
.use(fileUpload())
.use(defaultMiddlewares)
.use(paginationMiddleware)
.use(searchMiddleware)
.use(delayMiddleware)
.use(createdAt)
.use(daterange)
.use(absence)
.use(bankAccount)
.use(sort);
initLoginEndpoint(server, db);
initSickImagesEndpoint(server, db);
server.route("/sicks").all(filterByAccessRightFor(db));
server.route("/vacations").all(filterByAccessRightFor(db));
server.use(router);
server.listen(3001, "0.0.0.0", () => {
console.log("JSON Server is running");
});
repl("db", server, { db });
exports.db = db;
module.exports = server;
This is our index.js and apart from the db.json not updating, everything is working fine as expected. We have a script that is seeding the db, and when accessing a resource via GET the correct data gets retrieved.
Any ideas on that one?
Instead of providing a JSON object using require for the db.json file, you should provide a path to the json file.
// const source = require("./db.json");
const source = path.join(__dirname, 'db.json')
const router = jsonServer.router(source, {
foreignKeySuffix: "_id"
});
I have a site, implemented on NodeJS, base MongoDB, Mongoose plugin. Recently, the site began to fall about once a day. I recently found out that this is due to the lack of memory, which is due to the fact that active connections are being accumulated (db.serverStatus (). Connections.current). Perhaps this is not related, but I have a script on NodeJS, which is executed by crown every minute. It checks if there is a post with the current date in the documents. But I close the mongoose connection there, I don’t know what could be the problem. Actually this file contents:
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
const { new_time } = require("lib/functions");
const push = require("lib/push");
const apiCallback = require("middleware/socket/apiCallback");
const mongoose = require("lib/mongoose");
const User = require("models/User");
const Post = require("models/Post");
(async () => {
let currentPost = await Post.findCurrent(1);
if (currentPost) {
await currentPost.setPublished(1);
await apiCallback.call({
roomName: "index",
event : "posts.new",
data : {
post: {
id: currentPost._id.toString()
}
}
});
await push.sendAll({
// unnecessary data
});
}
await mongoose.connection.close();
process.exit(0);
})();
app.js:
const path = require("path");
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const expressSession = require("express-session");
const MongoStore = require("connect-mongo")(expressSession);
const conf = require("conf");
const mongoose = require("lib/mongoose");
const expressSessionConfig = conf.get("session");
expressSessionConfig.cookie.expires = new Date(new Date().getTime() + 60 * 60 * 24 * 30 * 1000);
expressSessionConfig.store = new MongoStore({
mongooseConnection: mongoose.connection
});
const templateDir = path.join(__dirname, conf.get("template_dir"));
app.engine("ejs", require("ejs-locals"));
app.set("views", templateDir);
app.set("view engine", "ejs")
app.use(express.static("frontend"));
app.use(cookieParser());
app.use(expressSession(expressSessionConfig));
app.use(bodyParser.urlencoded({
extended: true
}));
require("routes")(app);
app.listen(conf.get("app_port"));
app.io.js (socket server on socket.io):
const fs = require("fs");
const path = require("path");
const app = require("express")();
const bodyParser = require("body-parser");
const apiCallback = require("middleware/socket/apiCallback");
const conf = require("conf");
const sslPath = conf.get("sslPath");
const sslOptions = {
key : fs.readFileSync(path.join(sslPath, "key.key")),
cert: fs.readFileSync(path.join(sslPath, "crt.crt"))
};
const server = require("https").Server(sslOptions, app);
const io = require("socket.io")(server);
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(conf.get("api_callback:path"), apiCallback.watch(io));
require("routes/socket")(io);
server.listen(conf.get("socket_port"));
routes/socket.js:
const { in_array } = require("lib/functions");
const loadUser = require("middleware/socket/loadUser");
const User = require("models/User");
module.exports = io => {
io.on("connection", async socket => {
let query = socket.handshake.query || {};
let { ssid } = query;
ssid = ssid || "";
let user = socket.user = await loadUser(ssid);
let oldPageName = null;
User.setOnline(user._id, 1);
socket.on("setPageName", pageName => {
if (oldPageName) socket.leave(oldPageName);
oldPageName = pageName;
socket.join(pageName);
});
socket.on("disconnect", () => {
socket.leave(oldPageName);
User.setOnline(user._id, 0);
});
});
};
Tell me how to properly close connections so that they do not remain in memory and do not load the server to such an extent that it kills the process of the MongoDB daemon?
your code has no issues, you should go for connection pooling. your issue would automatically resolve. you will have a pool of connections whenever any api needs a db conenction. connection would be picked up from the pool and after completing db operation connection wouldn't be destroyed instead it would be returned back to the pool, in this manner your product's performance would be increased along with resolution to this issue.
https://mongoosejs.com/docs/connections.html