2017-06-29 68 views
0

我遇到问题,而当我重新启动Node/Koa.app时,MongoDB实例中存在的任何数据都将被删除。此应用程序使用Mongoose连接到本地Mongo实例。当我使用Mongoose重新启动NodeJS/Koa.app时,Mongo数据被删除

这里是我的代码:

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); 
}); 

MongoDB的配置URL上述模块中所引用的是:

mongo: { 
     url: 'mongodb://localhost:27017/degould_login' 
    } 

和我的猫鼬模型:

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'); 

和一个插入数据的功能

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) => { 

当我启动应用程序并使用注册函数向MongoDB填充数据时,我可以看到数据正确保存到MongoDB实例中。

但是,重新启动应用程序时,所有这些记录被删除有什么是在我的代码中造成这种情况?我不可能在开发过程中不得不在每次重新启动应用程序时继续输入数据。

+0

这可能是你的问题:mongoose.connection.db.dropCollection(e.name) –

+0

是的。我觉得自己没有发现那个白痴......你能否把它作为下面的答案,我会接受它。谢谢 – devoncrazylegs

回答

1

你的问题是这一行:

mongoose.connection.db.dropCollection(e.name); 

...您的收藏正在对猫鼬掉落“连接”事件。

+0

修复它,谢谢! – devoncrazylegs

相关问题