【问题标题】:Node.js: How to get the incorrect fields in the Error objectNode.js:如何在错误对象中获取不正确的字段
【发布时间】:2018-01-16 15:34:34
【问题描述】:

我在下面的架构中有唯一的必填字段。

当其中任何一个为空时返回错误。

如何在 Error 对象中找到路径以及哪些字段留空的信息?

var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
 
var Schema = mongoose.Schema;

var kullaniciShema = new Schema({
    gsm: String,
    email: String,
    kullaniciAdi: { type: String, required: true, unique: true },
    sifre: { type: String, required: true},
}, { collection: 'kullanici' });

kullaniciShema.plugin(uniqueValidator);

var Kullanici = mongoose.model('Kullanici', kullaniciShema);

module.exports = Kullanici;

下面是我将提交的数据保存到数据库中的控制器。一些传入的数据是空的,所以我收到了留空字段的错误。

如何在Error 对象中找到不正确的字段?

var yeniKullanici = new Kullanici({
    gsm: req.body.gsm,
    email: req.body.email,   
    kullaniciAdi: req.body.kullaniciAdi,
    sifre: req.body.sifre,
});

yeniKullanici.save(function(err){
    if (err) {
        //var error=new err("hata");
        //console.log(error.path);
        selectAllFromKullanici((result) => { 
            //console.log(forUsersError.length);
            forUsersError[forUsersError.length] = assert.equal(error.errors['ad'].message, 'Path `name` is required.');
            res.render("kullanicilar", { kullanicilar: result, hata: forUsersError });
        })
    } else {
        selectAllFromKullanici((result) => { 
           res.render("kullanicilar", { kullanicilar: result });
        })
    }
});

对不起,我的英语不好。

【问题讨论】:

标签: javascript node.js mongoose


【解决方案1】:

在您尝试遇到故障并从错误消息中提取数据之前,我会检查这些字段是否为空,这可能会因未知错误而失败。

【讨论】:

    猜你喜欢
    • 2013-07-07
    • 1970-01-01
    • 2012-02-20
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    • 2020-04-05
    • 1970-01-01
    相关资源
    最近更新 更多