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);
});
});