gpt4 book ai didi

node.js - Mongoose 到对象

转载 作者:太空宇宙 更新时间:2023-11-04 01:46:17 26 4
gpt4 key购买 nike

我有以下 Mongoose 模式:

const UserSchema = new Schema({
email: {
type: String,
minlength: 1,
required: true,
trim: true,
unique: true,
validate: {
validator: isEmail,
message: '{VALUE} is not a valid email.',
},
},
emailPhrase: {
type: String,
},
tokens: [
{
access: {
type: String,
required: true,
},
token: {
type: String,
required: true,
},
},
],
});

以及以下预 Hook :

UserSchema.pre('save', function (next) {
const user = this;

if (!user.toObject().tokens[0].token) {
// do something
next();
} else {
// do something else
next();
}
});

问题是,即使 tokens 属性完全为空,第一种情况(执行某些操作)也不会运行。我在这里做错了什么?

最佳答案

您需要更改 pre hook 方法中的 if :

UserSchema.pre('save', function (next) {
const user = this;

if (user.toObject().tokens && user.toObject().tokens.length > 0) {
console.log('do something');
next();
} else {
console.log(' do something else');
next();
}
});

验证数组的方法有很多,这里有一些选项的链接: Check is Array Null or Empty

关于node.js - Mongoose 到对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51340503/

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