I am trying to connect to MongoDb using mongoose. Here is the code I am using to connect:
controller.js
const conn = mongoose.createConnection(db, {
useNewUrlParser: true,
useUnifiedTopology: true
})
conn.once('open', () => {
console.log(`${req.body.db} DB connected`)
const model = conn.model(`item`, Item, req.body.collection)
let stuff = uploadToS3(req.files)
stuff.then(paths => {
const newItem = new model({
nameOfItem: req.body.name,
pictures: paths,
description: req.body.description,
year: req.body.year,
favorite: req.body.favorite
})
//save data to MongoDB
newItem.save()
.then(item => {
console.log(item)
res.json(item)
})
.catch(err => console.log(err))
conn.close()
})
})
I don’t think this matters, but I will state it anyway. I am using a single schema for several different databases and collections. Here is the schema:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const pictureSchema = new Schema({
name: String,
path: String
})
const itemSchema = new Schema({
nameOfItem: { type: String, required: true },
pictures: [pictureSchema],
description: String,
year: String,
favorite: {type: Boolean, default: false}
})
module.exports = itemSchema
And I am pulling the schema into the controller using this:
const Item = require('../models/item.model')
Here is the output:
bottles DB connected
{
fieldname: 'photos',
originalname: 'DSCN5104.JPG',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'uploads/',
filename: '1c17e793b340658f14bcc92c98444d95',
path: 'uploads\1c17e793b340658f14bcc92c98444d95',
size: 2107729
}
MongoNotConnectedError: MongoClient must be connected to perform this operation
at getTopology (C:UsersuserOneDriveDesktopProjectservernode_modulesmongodblibutils.js:367:11)
at Collection.insertOne (C:UsersuserOneDriveDesktopProjectservernode_modulesmongodblibcollection.js:150:82)
at NativeCollection.<computed> [as insertOne] (C:UsersuserOneDriveDesktopProjectservernode_modulesmongooselibdriversnode-mongodb-nativecollection.js:200:33)
at model.Model.$__handleSave (C:UsersuserOneDriveDesktop\Projectservernode_modulesmongooselibmodel.js:294:33)
at model.Model.$__save (C:UsersuserOneDriveDesktopProjectservernode_modulesmongooselibmodel.js:374:8)
at C:UsersuserOneDriveDesktopProjectservernode_moduleskareemindex.js:281:16
at C:UsersuserOneDriveDesktopProjectservernode_moduleskareemindex.js:78:15
at processTicksAndRejections (internal/process/task_queues.js:79:11)
bottles DB closed
What confuses me is that it says that it is connected and giving me that error at the same time. Any help is appreciated.