【问题标题】:inter property reference with in an object using Mongoose使用 Mongoose 的对象中的属性间引用
【发布时间】:2016-02-01 20:52:12
【问题描述】:

我正在使用 Mongoose,我的模型就像-

{
first_name:{
 type:String
},
lastName:{
 type:String
}
name:{
 type:String
}
}

我希望每当我使用 firstName 和 lastName 创建对象时,名称字段应自动设置为 firstName+" "+ lastName。

我可以像在 Java 中那样使用一些东西吗-

name = this.firstName+this.lastName 

提前致谢。

【问题讨论】:

标签: node.js mongoose


【解决方案1】:

pre方法试试

schema.pre('save', function (next) {
    this.name = this.lastName + this.firstName;
    next();
});

var Person = mongoose.model('Person', schema);

function saveData() {
    var p = new Person({
        lastName: 'DD',
        firstName: 'ss'
    });

    p.save(function(err, obj) {
      console.log(obj);
    }); 
}

结果

{ __v: 0,
  name: 'DDss',
  lastName: 'DD',
  firstName: 'ss',
  _id: 56af4489b81a1f2903a13608 }

【讨论】:

    【解决方案2】:

    我个人更喜欢使用虚拟全名。

    var PersonSchema = new Schema({
        name: {
            first: String
          , last: String
        }
    });
    PersonSchema
    .virtual('name.full')
    .get(function () {
        return this.name.first + ' ' + this.name.last;
    }); 
    

    【讨论】:

      猜你喜欢
      • 2013-11-25
      • 2016-10-27
      • 1970-01-01
      • 1970-01-01
      • 2019-12-27
      • 2022-09-23
      • 2016-10-09
      • 1970-01-01
      • 2018-04-15
      相关资源
      最近更新 更多