Search code examples
node.jsgoogle-cloud-datastore

Result not getting stored in Google datastore DB


Not able to save the data in Google Datastore DB not getting any error, can somebody help me to find the fix

Console.log result as below

entityKey: Key { namespace: undefined, kind: 'User', path: [Getter] }, entityData: { firstname: 'Abcd', lastname: 'Abcd', email: 'abcd@gmail.com', password: '123454', createdOn: 'Abcd', [Symbol(KEY)]: Key { namespace: undefined, kind: 'User', path: [Getter] } }, Ref - https://www.npmjs.com/package/gstore-node

const express = require('express');
const router = express.Router();
const { check, validationResult } = require('express-validator');
var User =require('../models/user');

//get register page
router.get('/register',function(req,res){
    res.render('register')
});

//get login page
router.get('/login',function(req,res){
    res.render('login')
});


router.post('/register',  [
        check('Name').isEmpty().withMessage('The Name is required'),
        check('Email').isEmail().withMessage('Email is requried'),
        //check('Password').isEmpty().withMessage('pass is requried'),
        //check('Password','Password is Requried').isEmpty(),
       // check('Password2','Password Not Match').equals('password2'),
 
      ], (req, res,next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    res.render('register',{
        error:errors.mapped()
    })
  }else{

    console.log()
    
    const newUser = new User ({
        firstname:req.body.name,
        lastname:req.body.name,
        email :req.body.Email,
        password :req.body.Password,
        createdOn:req.body.name
      });
      console.log("Data1",newUser)
     
        const createUser = (req, res) => {
        const entityData = User.sanitize(req.body);
        const user = new User(entityData);
        console.log("Data2",createUser)
        user.save()
            .then((entity) => {
                res.json(entity.plain()); 
            })
            .catch((err) => {
                // If there are any validation error on the schema
                // they will be in this error object
                res.status(400).json(err);
            })
    };
  
      req.flash('success_msg','you are registered and can login now');
      res.redirect('/users/login');

  }
  
});

module.exports=router;

const { Gstore, instances } = require('gstore-node');
const { Datastore } = require('@google-cloud/datastore');
 
const gstore = new Gstore();
const datastore = new Datastore({
    projectId: 'sinuous250616',
});
 
gstore.connect(datastore);
 
// Save the gstore instance
instances.set('unique-id', gstore);


const bcrypt = require('bcrypt');
 
// Retrieve the gstore instance
const ggstore = instances.get('unique-id');
const { Schema } = ggstore;
 
/**
 * A custom validation function for an embedded entity
 */
const validateAccessList = (value, validator) => {
    if (!Array.isArray(value)) {
        return false;
    }
 
    return value.some((item) => {
        const isValidIp = !validator.isEmpty(item.ip) && validator.isIP(item.ip, 4);
        const isValidHostname = !validator.isEmpty(item.hostname);
 
        return isValidHostname && isValidIp;
    });
}
 
//Create the schema for the User Model
const userSchema = new Schema({
    firstname: { type: String, required: true },
    lastname: { type: String, optional: true  },
    email: { type: String, validate: 'isEmail', required: true },
    password: { type: String, read: false, required: true },
    createdOn: { type: String, default: gstore.defaultValues.NOW, write: false, read: false }

});

/**
 * List entities query shortcut
 */
const listSettings = {
    limit: 15,
    order: { property: 'lastname' }
};
userSchema.queries('list', listSettings);
 
/**
 * Pre "save" middleware
 * Each time the entity is saved or updated, if there is a password passed, it will be hashed
*/
function hashPassword() {
    // scope *this* is the entity instance
    const _this = this;
    const password = this.password;
 
    if (!password) {
        return Promise.resolve();
    }
 
    return new Promise((resolve, reject) => {
        bcrypt.genSalt(5, function onSalt(err, salt) {
            if (err) {
                return reject(err);
            };
 
            bcrypt.hash(password, salt, null, function onHash(err, hash) {
                if (err) {
                    // reject will *not* save the entity
                    return reject(err);
                };
 
                _this.password = hash;
 
                // resolve to go to next middleware or save method
                return resolve();
            });
        });
    });

 
// add the "pre" middleware to the save method
userSchema.pre('save', hashPassword);
 
/**
 * Export the User Model
 * It will generate "User" entity kind in the Datastore
*/
module.exports = gstore.model('User', userSchema);


Solution

  • *I think there is a problem with User model **

    You should have a User model like this in /models/user.js (put models at the root of your application) to define User:

    const { instances } = require('gstore-node');
    const bscrypt = require('bcrypt-nodejs');
    
    // Retrieve the gstore instance
    const gstore = instances.get('unique-id');
    const { Schema } = gstore;
    
    var usersSchema = new Schema({
        firstname:{type:String},
        lastname:{type:String},
        email:{type:String},
        password :{type:String},
        createdOn: Date
    })
    
    var User = gstore.model('User', usersSchema);
    
    module.exports = User;
    

    And you forgot to use to save with save()

    var newUser = new User ({
            firstname:req.body.name,
            lastname:req.body.name,
            email :req.body.Email,
            password :req.body.Password,
            createdOn: new Date() // there is a problem here.... use new Date()
          });
    
    newUser.save(); //<======= it is abscent so it won't save