Preventing MongoDB Injection with Proper Query Construction
Owner: SnippetBot
Created: 2026-10-16 00:00:24
Size: 0.90 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Assuming 'mongoose' is installed and connected
const User = require('./models/User'); // Mongoose model
async function findUserSecurely(username) {
try {
// Mongoose automatically sanitizes values passed in query objects,
// preventing injection attacks.
const user = await User.findOne({ username: username });
// Do NOT construct queries like this: `User.find({ $where: "this.username == '" + username + "'" })`
// That would be vulnerable to injection if 'username' is not sanitized.
if (user) {
console.log('User found:', user.username);
return user;
} else {
console.log('User not found.');
return null;
}
} catch (error) {
console.error('Error finding user:', error);
throw error;
}
}
// Usage:
// findUserSecurely('testuser');
// findUserSecurely("admin' --"); // This will safely search for literal "admin' --" not execute arbitrary JS