1

trim() and split()保存しようとすると、コードの最後にエラーが表示されます。

エラー

    {"error":{"message":"Object #<Object> has no 
method 'trim'","stack":"TypeError: Object #<Object> has no method 'trim'\n    
at model.<anonymous> ...}}

モデル

var mongoose = require('mongoose')
    , Schema = mongoose.Schema
    , ObjectId = Schema.ObjectId;

var ContactSchema = new Schema({
    name: {
        first: String,
        last: String,
        clean: {type: String, unique: true}
    },
    email: String,
    added: Date
});

ContactSchema
    .index({name: {last: 1, clean: 1}, email: 1})
    .pre('save', function (next) {
        if (!this.added) this.added = new Date();
        this.name.clean = (this.name.first + '-' + this.name.last).toLowerCase();
        next();
    })
    .virtual('name.full').get(function () {
        return this.name.first + ' ' + this.name.last;
    })
    .set(function (name) {
        var split = name.trim().split(' ');
        this.name.first = split[0];
        this.name.last = split[1];
        this.name.clean = split.join('-').toLowerCase();
    });



exports.contactModel = mongoose.model('Contact', ContactSchema, 'Contact');

アップデート

req.body.name passed which contains object {first:'s', last:'d'}

app.post('/api/contact', function (req, res, next) {
    new Contact({
        name: {
            full: req.body.name 
        },
        email: req.body.email
    }).save(function (err, docs) {
            if (err) return next(err);
            res.send(docs);
        });
});
4

0 に答える 0