【问题标题】:javascript access form data from inside mongoose schema hooksjavascript 从 mongoose 模式挂钩内部访问表单数据
【发布时间】:2019-06-06 15:28:08
【问题描述】:

我有一个表单,我将其内容分成两个 mongodb 架构

我想直接在 mongoose 模式挂钩中读取 node.js/express.js 中的变量 通过模式的 pre 或 post 钩子。这些是我的文件

express.js

var firstName = req.body.first_name;
var lastName = req.body.last_name;
var fullName = firstName+' '+lastName;
var employmentDate = req.body.employment_date;
var responsibility = req.body.responsibility;

userschema.full_name = fullName;
userschema.first_name = firstName;
userschema.last_name = lastName;
userschema.save(function (err, result){

});
/******************express UPDATE START**********/
    user  = new userschema(req.body)
    employment = new employmentObject(req.body)

    employment.employment_date= employmentDate;
    employment.responsibility= responsibility;
/******************express UPDATE ENDS**********/

Schema.js

var userSchema = mongoose.Schema({
        full_name           : String,
        other_name          : String,
        last_name           : String,
        email               : String
        });

userSchema.pre('save', function (){
    //obtain values from form field
    var field1 = employmentDate;
    var field2 = responsibility;

    const employmentObject = this.model('employment-detail');   
    /******************schema UPDATE START**********/
    var emp_Date = employmentObject.employment_date;
    var duties = employmentObject.responsibility;
    /******************schema UPDATE ENDS**********/

    employmentObjectins = new employmentObject({
                                'employment_date': formField1,
                                'responsibility' :formField2
                        });

        employmentObjectins.save(function (err){
        if(err){
            console.log(err+' error saving object');
        }
        else{
            console.log('no error in saving object');
        }
    });
});

这是刚刚总结的内容,比这个还长。但这是主要概念。 主要领域是将 express.js 内容放入模型的架构中

更新

employmentDate 和责任不在 userSchema 中,但在employmentSchema 中 如何获取不在 userSchema (主模式)中但在就业模式中的字段 (第二种模式)

第二次更新

通过上面的修改,它会产生错误 ParallelSaveError:无法并行保存()同一个文档。文件:

我做错了什么

第三次更新

当我根据你所说的进行修改时,我发现当我有两个模型时 在 express.js 中声明了它们的模型字段/变量,我将第二个模型称为 第一个模型的预钩它给了我这个错误 不能同时保存()同一个文档多次。

修改代码后。这些是存在的文件

Express.js

var firstName = req.body.first_name;
var lastName = req.body.last_name;
var fullName = firstName+' '+lastName;
var employmentDate = req.body.employment_date;
var responsibility = req.body.responsibility;

userschema.full_name = fullName;
userschema.first_name = firstName;
userschema.last_name = lastName;
userschema.save(function (err, result){

});

employment.employment_date= employmentDate; <---
employment.responsibility= responsibility; <---
//I believe that I would need to declared this in order to use it in the schema

user  = new userschema(req.body)
employment = new employmentObject(req.body)

userschema.js

var userSchema = mongoose.Schema({
        full_name           : String,
        other_name          : String,
        last_name           : String,
        email               : String
        });

userSchema.pre('save', function (){
    //obtain values from form field
    var field1 = employmentDate;
    var field2 = responsibility;

    const employmentObject = this.model('employment-detail');   
    var emp_Date = employmentObject.employment_date;<-- I am calling what I declared earlier
    var duties = employmentObject.responsibility;<-- I am calling what I declared earlier in express
   **//when I declared above two lines it brings up the error **
   **//Can't save() the same doc multiple times in parallel.**
    employmentObjectins = new employmentObject({
                                'employment_date': emp_Date,
                                'responsibility' :duties
                        });

        employmentObjectins.save(function (err){
        if(err){
            console.log(err+' error saving object');
        }
        else{
            console.log('no error in saving object');
        }
    });
});

【问题讨论】:

    标签: javascript node.js express mongoose


    【解决方案1】:

    这就是我在项目中所做的

    let userData = new UserModel(req.body);
    let employmentData = new EmploymentModel(req.body);
    

    这将保存 req.body 中匹配架构的所有参数

    【讨论】:

    • 你是热潮。如果matrix是真的我会通过电脑给你一个拥抱非常感谢你,我真的很感激。请问属于不在主模型中的其他模型的字段呢?请看上面的评论
    • 非常感谢。我目前收到一个错误'Can\'t save()同一个文档并行多次{文档ID例如562422hkjhkjhjkhk}。我会用最新结果回复你
    • 我添加了产生错误的修改'Can\'t save()同一个文档并行多次
    • 不看代码很难判断是什么原因造成的
    • 非常感谢您,我想为您的答案投票,但我没有足够的积分
    【解决方案2】:
    const Schema = mongoose.Schema;
    const bcrypt = require('bcrypt-nodejs');
    const crypto =  require('crypto')
    const Userschema = new Schema({
        email:{
                type:String,
                unique:true,
                lowercase:true
        },
        name:String,
        password:String,
        picture:String,
        isSeller:{type:Boolean,default:false},
        address:{
            addr1:String,
            addr2:String,
            city:String,
            state:String,
            country:String,
            postalCode:String
        },
        created:{type:Date,default:Date.now}
    });
    // this pre function do encryption before saving the password into database
    Userschema.pre('save',async function(next){
        var user  =this;
        console.log(user.password);
        if (!user.isModified('password')) {
            return next();
        }
    
        bcrypt.hash(user.password,null,null,(err,hash)=>{       
            if (err) {
                return next(err);
            }
           user.password = hash;
            next();
           **this is my mistake I miss "next()"**
        })
    })
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-18
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 2018-02-21
      • 2011-03-13
      • 2016-12-15
      • 1970-01-01
      相关资源
      最近更新 更多