Create in-memory database using mongodb-memory-server and mongoose - javascript

I want to create a in-memory database using mongodb-memory-server and mongoose. Can anyone show the correct way to do it.

From version 7 and above
// this no longer works
const mongo = new MongoMemoryServer();
const uri = await mongo.getUri(); // ERROR: instance not started
// it is now
const mongo = await MongoMemoryServer.create();
const uri = mongo.getUri();
https://nodkz.github.io/mongodb-memory-server/docs/guides/migration/migrate7/#no-function-other-than-start-create-ensureinstance-will-be-starting-anything

Read the documentation here and came accross the following solution.
const mongoose = require('mongoose');
const { MongoMemoryServer } = require('mongodb-memory-server');
const mongoServer = new MongoMemoryServer();
mongoose.Promise = Promise;
mongoServer.getUri().then((mongoUri) => {
const mongooseOpts = {
useNewUrlParser: true,
useFindAndModify: false,
useCreateIndex: true,
useUnifiedTopology: true,
};
mongoose.connect(mongoUri, mongooseOpts);
mongoose.connection.on('error', (e) => {
console.log(e);
});
mongoose.connection.once('open', () => {
console.log(`MongoDB successfully connected to ${mongoUri}`);
});
});
module.exports=mongoose.connection;

Related

How can I connect to GridFS bucket from my controller

I'm trying to use a gridfs bucket to store uploaded files. I have the upload sorted, but downloading is a bit more tricky.
to retrieve files i need to access the bucket instance, which I create in the database connecting function:
const connectDB = async () => {
try {
// connection
const conn = mongoose.createConnection(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// init gfs
let gfs;
conn.once("open", () => {
// init stream
gfs = new mongoose.mongo.GridFSBucket(conn.db, {
bucketName: "assets",
});
});
return gfs;
} catch (err) {
console.error(err.message);
process.exit(1);
}
};
I think I'd end up with multiple connections and buckets if I called it again from my controller, is this the case?
What's the best way to access the gfs object from my controller?
At the start of application, call mongoose.connect and use mongoose.connection anywhere else, it will use the default connection automatically. For example:
index.js
const mongoose = require("mongoose");
mongoose.set("strictQuery", false);
mongoose.connect("mongodb://127.0.0.1:27017/test");
bucket.js
const mongoose = require("mongoose");
const { GridFSBucket } = require("mongodb");
const bucket = new GridFSBucket(mongoose.connection); // autouse default connection
module.exports = bucket;
controller.js
const bucket = require('./bucket')
router.post("/", (req, res) => {
const stream = bucket.openUploadStream("test.txt");
stream.write("test");
stream.on("finish", (file) => {
res.send("done");
});
stream.end();
});

Mongoose model queries hang in node

I have a database file where I set up my schemas/models for mongo and export them. Whenever I reference the models for queries in other files, then run the file in node, it hangs. I get my data back but I have to manually close node. I have tried other solutions like mongoose.disconnect() at the end of my database file but that breaks my query.
database.js
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true, useUnifiedTopology: true })
const exampleSchema = new mongoose.Schema({
name: String,
stuff: {}
})
const Example = mongoose.model('Example', exampleSchema)
module.exports = {
Example
}
function.js
const { Example } = require('../database')
const doSomething = async (name) => {
const data = await Example.find({ name: name })
}
doSomething('jwhunt19')
use this url mongodb://localhost:27017/test for database connection
mongoose.connect('mongodb://localhost:27017/test',
{ useNewUrlParser: true, useUnifiedTopology: true })
27017 is your port number for databse coonection, if you want ,you can change it to another number
jsut try like this:
const mongoose = require('mongoose');
const connection = mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true, useUnifiedTopology: true })
const exampleSchema = new mongoose.Schema({
name: String,
stuff: {}
})
const doSomething = async (name) => {
const data = await Example.find({ name: name })
}
doSomething('jwhunt19')
const Example = connection.model('User', exampleSchema);
module.exports = connection;
function.js
const connection = require("./database");
const Example = connection.models.Example ;

MongoDB client in Node

Im trying to connect mongodb in node.js and take the link to client to the outer variable.
I need to create a module that would return a result of .find() method. How can i do this?
const MongoClient = require('mongodb').MongoClient
let client
mongoClient = new MongoClient('mongodb://localhost:27017/', {useUnifiedTopology: true, useNewUrlParser: true})
mongoClient.connect((err, db) => {
if (err) {
return console.log(err)
}
client = db
})
const database = client.db('db')
const collection = database.collection('collection')
client.close()
And the error
const database = client.db('db')
^
TypeError: Cannot read property 'db' of undefined
As the comment suggests, you can use async/await to wait for the connection to be established, and do the error handling with a try/catch statement:
try {
const client = await mongoClient.connect()
const database = client.db('db')
const collection = database.collection('collection')
} catch(e) {
console.log(e)
}
Don't forget to use it in an async function.
Update
An async function example, you may want to return the collection:
const getData = async () => {
try {
mongoClient = new MongoClient('mongodb://localhost:27017/', {useUnifiedTopology: true, useNewUrlParser: true})
const client = await mongoClient.connect()
const database = client.db('db')
const collection = database.collection('collection')
client.close()
return collection
} catch(e) {
console.log(e)
}
}
after uri you must define db name
mongoClient = new MongoClient('mongodb://localhost:27017/', {useUnifiedTopology: true, useNewUrlParser: true})
like this
mongoClient = new MongoClient('mongodb://localhost:27017/shop', {useUnifiedTopology: true, useNewUrlParser: true})

How to separate the mongoose connect method to another JS file?

For my discord bot, I was thinking of separating the mongoose connect method and other initialization to a separate JS file. I was able to move everything except for the connect method. I don't know how this could be done.
Try below code
// Declare mongoose as global
global.mongoose = require('mongoose');
// In Separate file
const url = "Your URL";
//BUILD A CONNECTION
mongoose.connect(url).then(() => { console.log('Connected To database :)')})
.catch( err => console.log('error', err));
module.exports.mongoose = mongoose
// Schema File
const users = new mongoose.Schema({
name : String,
}, {
timestamps : true
})
module.exports = mongoose.model('users', users);
// In model Path
const usersModel = require('Schemas/users')
now you can use usersModel to query documents/table
// suppose this filename is, mongoose.db.config.js
const mongoose = require("mongoose");
function mongooseConnectDB(uri) {
mongoose
.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
})
.then((result) =>
console.log("Mongoose connected to ", result.connections[0].host)
)
.catch((err) => console.log("error connecting to the database", err));
}
module.exports = mongooseConnectDB;
Now in your app(main.js/index.js/server.js), you can do simply like this
const mongooseConnectDB = require("./mongoose.db.config");
mongooseConnectDB('url_of_your_db');

Working on Nodejs that uses MongoDB . I am getting TypeError: Cannot read property 'Promise' of undefined

When I am trying to enter new dishes into the collection it returns the new dishes but after that it shows 'TypeError: Cannot read property 'Promise' of undefined'.
Tried uninstalling promise and installing again.
Also I tried with es6-promise.
dishes.js
const mongoose= require('mongoose');
const Schema = mongoose.Schema;
const dishSchema = new Schema({
name: {
type : String,
required : true,
unique : true
},
description :{
type : String,
required : true
}
},{
timestamps : true
});
var Dishes = mongoose.model('Dish',dishSchema);
module.exports = Dishes;
And index.js
const mongoose = require('mongoose');
var Promise = require('es6-promise').Promise;
mongoose.Promise = require('bluebird');
const Dishes = require('./models/dishes');
const url = 'mongodb://localhost:27017/conFusion';
const connect = mongoose.connect(url);
connect.then((db) => {
console.log('Connected correctly to Server');
var newDish = Dishes({
name : "Uthapizza",
description : 'test'
});
newDish.save()
.then((dish) =>{
console.log(dish);
return Dishes.find({}).exec();
})
.then((dishes) =>{
console.log(dishes);
return db.Collection('dishes').drop();
})
.then(() =>{
return db.close();
})
.catch((err) => {
console.log(err);
});
});
The code is working fine but I don't know why it is throwing an error in the end.
Try using this method. I hope it helps.
const url = 'mongodb://localhost:27017/conFusion';
const mongoose = require('mongoose');
// Note: use global.Promise instead of bluebird
mongoose.Promise = global.Promise;
const connect = mongoose.connect(url, {
useNewUrlParser: true,
promiseLibrary: global.Promise
});
....

Categories

Resources