[英]Mongoose ignore column from find, if the value is null
假设我有一个 mongoose model 和一个基于机会的值
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, "email": email, "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?
}
但这里的问题是我必须再次输入相同的内容,只是为了包含另一个字段。 有没有办法有条件地在搜索中包含一列?
可能有一种更简单/更好的方法来实现这一点,但在这种情况下我会做的是像这样构建一个 object。
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);
}
本质上,创建一个默认的 object,其中包含您的属性,该属性将始终存在。 然后检查你的 foo 值是否不是 null。 如果不是 null,则将其添加到您的查询中并将该查询 object 传递给查找。
您可以将查询提取到变量中,然后根据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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.