如何解决猫鼬忽略查找中的列,如果该值为空
假设我有一个猫鼬模型和一个基于偶然性的值
const findUser = async (username,email) => {
let foo = null
if (Math.random() > 0.5) foo = "hi" // `foo` now has a chance of turning from null to "hi"
UserModel.find({ "username": username,"email": email,"winner": foo === null ? 'EXCLUDE THIS SEARCH VALUE' : foo
}
^ This is some real code,in combination with some pseudo code ^
我可以这样实现:
const findUser = async (username,email) => {
let foo = null
if (Math.random() > 0.5) foo = "hi" // `foo` now has a chance of turning from null to "hi"
let result;
if(foo === null)
result = await UserModel.find({ "username": username,"email": email });
else
result = await UserModel.find({ "username": username,"winner": foo });
// ^^ Now I have to type the same thing all over again..
// I'm wondering if there is a way to include it conditionally?
}
但是这里的问题是我必须再次输入相同的内容,只是要包含另一个字段。有没有一种方法可以在搜索中适当地包含一列?
解决方法
可能有一种更简单/更好的方法来实现此目的,但是在这种情况下,我要做的就是构建一个像这样的对象。
const findUser = async (username,email) => {
let foo = null
let query = {
username,email
}
if (Math.random() > 0.5) foo = "hi" // `foo` now has a chance of turning from null to "hi"
if (foo != null) {
query.winner = foo;
}
UserModel.find(query);
}
基本上,创建一个默认对象,该对象中将始终带有您的属性。然后检查您的foo值是否不为null。并且,如果它不为null,则将其添加到查询中,然后将该查询对象传递到查找中。
,您可以将查询提取到变量中,然后根据foo
的值进行操作。
const findUser = async (username,email) => {
let foo = null
if (Math.random() > 0.5) foo = "hi"
const query = { username,email }
if (foo) {
query.winner = foo
}
const result = await UserModel.find(query)
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。