结果未存储在Google数据存储数据库中

时间:2019-08-24 06:09:02

标签: node.js google-cloud-datastore

无法将数据保存在Google Datastore DB中,没有出现任何错误,有人可以帮助我找到修补程序

Console.log结果如下

entityKey:密钥{名称空间:未定义,种类:'User',路径:[Getter]},   实体数据:    {名:“ Abcd”,      姓氏:“ Abcd”,      电子邮件:“ abcd@gmail.com”,      密码:“ 123454”,      createdOn:'Abcd',      [Symbol(KEY)]:密钥{名称空间:未定义,类型:'用户',路径:[Getter]}}, 参考-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);

1 个答案:

答案 0 :(得分:1)

*我认为用户模型**

有问题

/models/user.js(在应用程序的根目录放置模型)中应该具有这样的User模型来定义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;

您忘记了使用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