Mongoose Virtual无法正常工作

时间:2018-01-24 11:32:53

标签: node.js mongoose

我有一个mongoose Schema调用用户名,我试图在虚拟中连接用户名。当我在获取或执行这些模型中的函数中记录虚拟时,它返回undefined。

我参考了文档,并且示例是嵌套模型,我更喜欢当前模型而不是嵌套它。 我希望任何人都可以帮助我。

const Schema = mongoose.Schema;
const UserSchema = new Schema({ 
firstname: {
type: String,
lowercase: true,
required: true
},
lastname: {
type: String,
lowercase:true,
text: true,trim: true,
required: true},
middlename: {
type: String,
text: true,trim: true,
lowercase: true
 }
  UserSchema.virtual('fullname')
.get(function(){
  return this.firstname + ' ' + this.lastname;
})
.set(function(firstname, lastname) {
  firstname = this.firstname;
  lastname = this.lastname;
});
UserSchema.set('toObject', {virtuals: true});
UserSchema.set('toJSON', {virtuals: true});
  });
  const User = module.exports = mongoose.model('User', UserSchema);

2 个答案:

答案 0 :(得分:1)

试试这个:

const Schema = mongoose.Schema
const UserSchema = new Schema({ 
  firstname: {
    type: String,
    lowercase: true,
    required: true
  },
  lastname: {
    type: String,
    lowercase:true,
    text: true,
    trim: true,
    required: true
  }
})

UserSchema.set('toObject', { virtuals: true })
UserSchema.set('toJSON', { virtuals: true })

UserSchema.virtual('fullname')
  .get(function() {
    return this.firstname + ' ' + this.lastname
  })
  .set(function(newName) {
    var nameParts = newName.split(' ')
    this.firstname = nameParts[0]
    this.lastname = nameParts[1]
  })

const User = module.exports = mongoose.model('User', UserSchema)

然后你应该能够这样做:

var somebody = new User({
  firstname: 'Some',
  lastname: 'Body'
})

somebody.save(function(err, doc) {
  console.log(somebody.fullname) // Some Body

  doc.fullname = 'Another Person'

  doc.save(function(err, doc) {
    console.log(doc.fullname) // Another Person
  })
})

我希望这会有所帮助。

答案 1 :(得分:0)

我遇到了与虚拟相同的问题,返回“未定义”。 我通过不使用箭头函数解决了这个问题(感谢@Bradyo 的评论)。 所以Mongoose 5.12.7也不支持箭头函数。