I have this end point that creates a new server in my database, when I say server, it's just a server name. We have several gaming servers, so, we want to manage them from a website,
const createServer = asyncHandler(async (req, res) => {
const { gameName, serverName } = req.body;
const serverExist = await Server.findOne({ serverName });
if (!gameName || !serverName) {
res.status(400);
throw new Error("Please add game name / server name");
}
if (!serverExist?.isHidden) {
// if i set it to just serverExists it works
res.status(401);
throw new Error("Server exist");
}
//Get user using the id in the JWT
const user = await User.findById(req.user.id);
if (!user) {
res.status(401);
throw new Error("User not found");
}
const server = {
gameName,
serverName,
user: req.user.id,
};
await Server.create(server);
res.status(201).json(server);
});
Now, I'm checking if the server already exists in the database with serverExist
, it returns all the document about that server, all works good. It has a property called isHidden
, the time I set it in the if
statement, the server is not able to return any response. if I set if
statement to only if(serverExist)
, it does work, but I need it to work if the server was set to hidden so that a user could re-create it. I don't want to delete as it will be needed for later.
I checked all the returns and all seems ok, even the server object at the end does have the information. The problem is happening when I'm calling the create method. Don't know why adding serverExist.isHidden
makes it unable to create the document!
CodePudding user response:
You've got a little logic problem.
Consider these states when evaluating !serverExist?.isHidden
...
State | !serverExist?.isHidden |
---|---|
No record exists | true ⚠️ |
Record exists with isHidden: true |
false |
Record exists with isHidden: false |
true |
I would instead include the isHidden
parameter in your query and use the Server.exists() method
const serverExists = await Server.exists({ serverName, isHidden: true });
if (serverExists) {
// Server exists and is not hidden
res.status(409); // 409 Conflict is a better status than 401 Unauthorized
throw new Error("Server exists");
}