1

According to the documentation on the website it's obvious how to save the data to the database, but right now I'm facing a problem when I integrate with express. For some reason it doesn't want to save the data.

Here is a sample of the code:

db.js:

var loki = require('lokijs');

// create db
var db = new loki('db.json', { autoupdate: true });

exports.db = db;

user.js

var loki = require('lokijs');
var db = require('../db').db;

// create collection
var user = db.addCollection('User');

exports.createUser = function(firstName, lastName, email, password) {
 user.insert({
  firstName: firstName,
  lastName: lastName,
  email: email,
  password: password
 });
};

db.saveDatabase();

routes.js

var routes = require('express').Router();
var CryptoJS = require('crypto-js');
var User = require('./model/user');

routes.post('/register', function(req, res) {
 console.log(req.body);
 var firstName = req.body.fname;
 var lastName = req.body.lname;
 var email = req.body.email;
 var password = req.body.password;

// encrypt password
var cipher = CryptoJS.MD5(password);

// create user in db
User.createUser(firstName, lastName, email, password);

res.status(200).json({ success: 'Thanks for creating an account! A confirmation email has been sent to your inbox!' });
});

I know I'm not using a strong encryption, just playing around... At this point I don't know what i'm doing wrong. It should save.

Thanks for your help!

Mark
  • 1,603
  • 3
  • 13
  • 18
  • 3
    According to the doc, the `db.saveDatabase();` method handles the saving to the file system or memory, you should move it to the`createUser` method so that it gets called after the user creation – Akram Saouri Jan 23 '17 at 15:59
  • @AkramSaouri Oh wow yes it's working now. Thank you so much! Should've read the documentation in more details. – Mark Jan 23 '17 at 17:13
  • My pleasure buddy ^^ – Akram Saouri Jan 24 '17 at 11:23

0 Answers0