I am having an issue whereas any data that exists in my MongoDB instance is being removed when I restart my Node/Koa.app. This application uses Mongoose to connect to the local Mongo instance.
Here is my code:
app.js (I have code in there to output connection to the logger)
import Koa from 'koa';
import path from 'path';
import bodyParser from 'koa-bodyparser';
import serve from 'koa-static';
import mongoose from 'mongoose';
import Config from '../Config.js';
global.appRoot = path.resolve(__dirname);
const app = new Koa();
mongoose.connect(Config.mongo.url);
mongoose.connection.on('connected', (response) => {
console.log('Connected to mongo server.');
//trying to get collection names
let names = mongoose.connection.db.listCollections().toArray(function(err, names) {
if (err) {
console.log(err);
}
else {
names.forEach(function(e,i,a) {
mongoose.connection.db.dropCollection(e.name);
console.log("--->>", e.name);
});
}
});
});
mongoose.connection.on('error', (err) => {
console.log(err);
});
The MongoDB config url being referenced in the above module is:
mongo: {
url: 'mongodb://localhost:27017/degould_login'
}
and my Mongoose model:
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
let UserSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
lowercase: true
},
password: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
groupForUsers: [{ type: Schema.Types.ObjectId, ref: 'userGroups' }]
});
export default mongoose.model('users', UserSchema, 'users');
And one of the functions that inserts Data
async register(ctx) {
return new Promise((resolve, reject) => {
const error = this.checkRequiredVariablesEmpty(ctx, [ 'password', 'email' ]);
if(error.length) {
reject(new this.ApiResponse({
success: false,
extras: {
msg: this.ApiMessages.REQUIRED_REGISTRAION_DETAILS_NOT_SET,
missingFields: error
}}
));
}
this.userModel.findOne({ email: ctx.request.body.email }, (err, user) => {
if(err) {
reject(new this.ApiResponse({ success: false, extras: { msg: this.ApiMessages.DB_ERROR }}));
}
if(!user) {
let newUser = new this.userModel();
newUser.email = ctx.request.body.email;
newUser.username = ctx.request.body.username;
newUser.password = ctx.request.body.password;
newUser.save()
.then((err, insertedRecord) => {
When I start the app and populate data into the MongoDB using the register function I can see the data saves into the MongoDB instance correctly.
However, when restarting the application all of these records get removed Is there anything that is causing this in my code? It's impossible for me to have to keep inputting data on every app restart during development.
Your issue is with this line:
mongoose.connection.db.dropCollection(e.name);
...where your collections are being dropped on mongoose 'connected' event.