I am trying to soft delete nodes in Neo4J when a user soft deletes their account but when I perform the operation by soft deleting a User account without posts or comments the user node is not set to true.
In this case a User account may or may not have any post or comment nodes so I want to perform an OPTIONAL MATCH on those nodes and if any posts or comments are found, I need to set deleted = true for ALL posts and if any comments are found, I need to DETACH DELETE all of the comments.
Even if an account has no posts or comments I need the query to set deleted = true on the matched user object.
What am I doing wrong? How can I made the user node's property be set to true with the below query?
import neo4j from "neo4j-driver"
const softDeleteAccount = async (userId) => {
let driver = neo4j.driver(
process.env.NEO4J_URL,
neo4j.auth.basic(process.env.NEO4J_USERNAME, process.env.NEO4J_PASSWORD)
)
let session = driver.session()
try {
let query = `
MATCH (user:User {userId: $userId})
OPTIONAL MATCH (posts:Post {userId: $userId}) // User may not have any posts
OPTIONAL MATCH (comments:Comment {userId: $userId}) // User may not have any comments
WITH user, posts, comments
SET posts.deleted = true, user.deleted = true
// ^ for all posts & user, set deleted = true
DETACH DELETE comments // Delete comments & their relationships
`
await session.executeWrite((tx) =>
tx.run(query, {
userId,
})
)
} catch (err) {
console.log(err)
// return error
} finally {
await session.close()
}
// on application exit:
await driver.close()
}
export { softDeleteAccount }
CodePudding user response:
Please ensure you pass the value of this parameter as {userId: userId}
tx.run(query, {
userId: userId,
})
I tried your query by itself and it works well.