gpt4 book ai didi

node.js - Mongoose 虚拟不工作

转载 作者:搜寻专家 更新时间:2023-11-01 00:36:55 25 4
gpt4 key购买 nike

我有一个 mongoose Schema 调用用户名,我正在尝试在虚拟中连接用户名。当我在 get 中记录虚拟或在这些模型中执行函数时,它返回未定义。

我引用了文档,那里的例子是嵌套模型,我更喜欢当前模型而不是嵌套它。我希望任何人都可以帮助我。

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

最佳答案

试试这个:

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

希望对您有所帮助。

关于node.js - Mongoose 虚拟不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48421489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com