How to set an object as nullable in Javascript (NodeJS) - javascript

I keep getting an error: TypeError: Cannot read property 'doors' of null. I want to be able to set doors to be nullable, as to be able to avoid this error and simply hit the error response and return 404. However, I am not sure how to do this?
Here is my code:
Data.findOne({
'_id':'6182544c20d538aefe49def0',
'doors.id':doorId
}, {
'doors.$':1
}, function(err, data) {
if (err) {
res.status(404).send('No Matching Door Found')
} else if (data.doors[0].status === 'open') {
res.status(401).send('Door already unlocked')
} else {
res.status(200)
}
})
The error is hit on the third line, where It cannot find a doors object where the ID is equal to doorId.
I have tried setting doors.id to !doors.id, however, this then kept hitting the 404 regardless of what was being entered.
Any help is appreciated, thank you.

Well it seems that your entire query is wrong.
I would suggest first to try this query for your needs:
Data.findOne({
'_id':'6182544c20d538aefe49def0',
'doors.id':doorId
}, {
'doors.$':1
}).exec(function(err, data) {
if (err) {
res.status(404).send('No Matching Door Found')
} else if (data.doors[0].status === 'open') {
res.status(401).send('Door already unlocked')
} else {
res.status(200)
}
})
Then I recommend you to read more about MongoDB and Mongoose.

Related

Why does this javascript code not redirect the user after the metamask transaction?

I want to make a javascript code that does a metamask transaction and redirects the user to another page after the transation is completed. How easy this may sound, I can not figure it out.
My current code lets the user complete the transaction, but it does not redirect the user to another page. Instead, it gives this error: "MetaMask - RPC Error: invalid argument 0: json: cannot unmarshal non-string into Go value of type common.Hash"
I have looked it up, but I could not find any possible fix for my problem.
This is my code:
try {
// send the transaction
ethereum.send({
method: 'eth_sendTransaction',
params: [
{
to: contractAddress,
from: userAddress,
value: amt
},
],
}, (error, transactionHash) => {
if (error) {
console.error(error);
} else {
// check the status of the transaction using the transaction hash
ethereum.request({
method: 'eth_getTransactionReceipt',
params: [transactionHash],
}).then((receipt) => {
// check if the transaction was successful
if (receipt.status === '0x1') {
console.log(`Transaction was successful`);
// redirect to another page
window.location.href = "page.php";
} else {
console.log(`Transaction failed`);
}
}).catch((error) => {
// This is the line of code the error is assigned to:
console.error(error);
});
}
});
} catch (error) {
console.error(error);
}
});
} else {
document.getElementById("bericht").innerHTML = "Install Metamask before you continue";
return;
}
I have tried looking the error up on internet, but nothing significant showed up. Could anyone help? Thank you in advance!

Empty folder still persists after recursively deleting using fs.rmdir

I'm trying to delete a folder recursively but the folder itself is still there (empty) when using fs.rmdir(dest, { recursive: true });
Has anyone else come across this issue and if so how did you manage to fix it?
I'm using Node v14.17.0
A hacky solution to anyone else having the same issue:
fs.rmdir(dest, { recursive: true }, (err) => {
if (err) throw err;
try {
if (fs.existsSync(dest)) fs.unlinkSync(dest);
} catch (e) {
// handle error
return;
}
});

How to throw an error inside the pre handler in Hapi.js

I started using v17 of Hapi.js and I am running into issues when using the pre-handler.
I want to save a user into a database, but first I use the pre-handler to check if a user already exists. If the user exists, I want to throw an error. The structure of my route is as so...
module.exports = {
method: "POST",
path: "/users",
config: {
auth: false,
pre: [{ method: verify_unique_user}],
handler: create_user.create
}
}
The content of verify_unique_user is...
async function verify_unique_user(req, h) {
await User.findOne({
$or: [{email: req.payload.email}, {username: req.payload.username}]
},
(err, user) => {
if (user) {
// Check if username exists.
if (user.username === req.payload.username) {
throw Boom.badRequest("Username taken!");
}
// Check if email exists.
if (user.email === req.payload.email) {
throw Boom.badRequest("Email taken!");
}
}
});
return req;
}
Let's assume the user already exists in the database. Then an error will be thrown from either of the if statements. When this happens, I get the following error...
events.js:167
throw er; // Unhandled 'error' event
^
Error: Username taken!
at User.findOne (/Users/ericbolboa/Desktop/Warble/server/src/users/util/user_function.js:16:16)
This crashed my server. This is not what I want. If I throw an error in my handler function, the response looks like this...
{
"statusCode": 400,
"error": "Bad Request",
"message": "error"
}
But whenever I throw an error in the pre-handler, my server crashes. How can I throw errors properly?
Not sure if this is the source of the issue but you can simplify the async/await instead of using the callback
async function verify_unique_user(req, h) {
const user = await User.findOne({
$or: [{email: req.payload.email}, {username: req.payload.username}]
});
// Check if username exists.
if (user.username === req.payload.username) {
throw Boom.badRequest("Username taken!");
}
// Check if email exists.
if (user.email === req.payload.email) {
throw Boom.badRequest("Email taken!");
}
return req;
}
Take a look at the toolkit(h) and options.response.failAction of route.
A route can set response.failAction in options. There, you can format error messages, and send response, however you please. That includes errors thrown from pre handlers.
Edit: Every pre-handler can have it's own 'failAction' handler. You must do a response(...).takeover() if you want to halt the chain.

Trouble Returning Different Variables from Mongo using NodeJS

So I have a function that when you pass a username as an argument it queries a MongoDB database and returns the document containing that username. So in the function, I check to see if the document exists containing the username, and if it doesn't I return the document that has an empty string as the username. So kind of like, return default if doesn't exist. So I assume that if it doesn't find a matching document it returns an undefined object.
Ideally, I want a function that when called will either return a default document retrieved from a database when the username doesn't exist or return the corresponding document for the username passed as an argument. Maybe the problems are trying to read or return variables before they exist because of the asynchronous nature of the calls.
I really don't think major restructuring of the code is a good idea, because I'm trying to work with three asynchronous libraries and connect them all together. I have multiple asynchronous classes in recursive processing functions.
getContext(username = '') {
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/tc-db', function (err, db) {
if (err) {
console.log(err);
} else {
db.collection('chatters').findOne({ username: username }, function (err, results) {
if (err) {
throw err;
} else if (results === undefined) {
db.collection('chatters').findOne({ username: '' }, function (err, results) {
console.log('Notifier');
console.log('Get if Null: ' + JSON.stringify(results));
return JSON.stringify(results.context);
});
} else {
console.log('Notifier 2');
return JSON.stringify(results.context);
}
});
}
});
}
The actual error I'm getting alot when running the function, especially with a username that doesn't exist in the database is "Can't read property 'context' of null". Thank you guys so much for any help you can offer.

catch error: structure (127 [object] [object]) on neo4j cypher session

I have had a similar error before but that was caused by a syntax error in the .run statement.
I have looked this code over and over and can't find a syntax so I think something else is going on. This function is called by the passport deserializer and the value of "id" was confirmed using node-inspector. however, no matter which type of MATCH query I use, I get the same .catch error.
I have tried WHERE option and the direct option...they both work in the neo4j browser. Can someone see what I am not seeing
router.getUserByID = function (id, callback) {
session
.run ("MATCH (user {id(user) : {paramUserID}}) RETURN user",{paramUserID: parseInt(id)})
.then (function(result)
{
if ( !result.records[0])
{
console.log("unknow user by id");
session.close();
if (typeof callback==="function") {
return callback(null,false);
}
} // end of if not found
else
{
console.log("user by id found");
session.close();
if (typeof callback === "function") {
return callback(null,result);
}
}
})
.catch(function(err)
{
console.log("catch error: "+err);
});
} // end of get user by id
You cannot reference the Neo4j id of the node that way, you have to use a WHERE clause:
MATCH (user) WHERE id(user) = {paramUserID} RETURN user;
If you have an application id (almost always a good idea), then you could do:
MATCH (user {uuid: {paramUuid}}) RETURN user;
It would be better with a label though, because different entities could have the same id, and you can use a unicity constraint (which also indexes the values, so the query is faster):
CREATE CONSTRAINT ON (n:User) ASSERT n.uuid IS UNIQUE;
// Later
MATCH (user:User {uuid: {paramUuid}}) RETURN user;

Categories

Resources