结果未定义的 JS。我不能接受这个赞美



我无法得到avatar.path的结果,我该怎么做? 如果我把这个.nome,我正常接收,但我无法得到avatar.path的结果。

如果我写this.avatar.name = value,则会抛出以下错误:

(节点:6652) 未处理的承诺拒绝警告: 类型错误: 无法读取 未定义的属性"路径">

我需要获取avatar.path,因为我将用于返回URL

const UserSchema = mongoose.Schema(
{
nome: {
type: String,
require: true
},
email: {`enter code here`
type: String,
unique: true,
required: true,
lowercase: true
},
password: {
type: String,
required: true
},
passwordresetoken: {
type: String,
select: false
},
passwordresetexpires: {
type: Date,
select: false
},
usuario_validado: {
type: Boolean
},
cpf: {
type: String,
required: true
},
user_cuidador: {
type: Boolean
},
avatar: [
{
nome: {
type: String
},
path: { type: String, required: true }
}
],
createdAt: {
type: Date,
default: Date.now
}
},
{
toObject: {
getters: true,
setter: true,
virtuals: true
},
toJSON: {
getters: true,
setter: true,
virtuals: true
}
}
);

UserSchema.virtual("url").get(function() {
console.log(this.nome); // I receive right the name
console.log(this.avatar); // I receive undefined
// I need to return avatar.path 
return `http://localhost:300/files/${this.nome}`; // I can receive all the names right. But, I need avatar.path
});

avatar是一个数组

{
nome: {
type: String
},
path: { type: String, required: true }
}

定义如下

avatar: [
{
nome: {
type: String
},
path: { type: String, required: true }
}
],

也可以是undefined.

您在这里将其视为对象:this.avatar.name = value.

如果假设它始终是 1 的数组,则将其转换为对象:

avatar: {
nome: {
type: String
},
path: { type: String, required: true }
},

并确保在虚拟中签入空/未定义。如果您需要头像始终存在,那么如果没记错的话,您可以将头像设置为架构并需要它。

const AvatarSchema = mongoose.Schema({
nome: {
type: String
},
path: { type: String, required: true }
})

然后在你的UserSchema里面,你会引用它:

avatar: { type: AvatarSchema, required: true }

否则,您需要进行空/未定义检查:

UserSchema.virtual("url").get(function() {
console.log(this.nome); // I receive right the name
console.log(this.avatar); // I receive undefined
// if avatar is an array then I guess you just want the first one?
let avatarPath;
if(this.avatar && this.avatar.length) {
avatarPath = this.avatar[0].path
} 
// ... 
return avatarPath ? avatarPath : `http://localhost:300/files/${this.nome}`; 
});

如果您保持架构不变并尝试设置头像路径,那么您可以执行以下操作:

this.avatar = this.avatar || []
this.avatar.push({name: value})
// but it will fail to validate because path is required.

查看文档中的猫鼬子文档

编辑:

我忘了提到你在你的问题中,你指的是this.avatar.name但你的架构指的是nome而不是name

最新更新