Model Methods: $where

Executing JavaScript expressions arbitrarily during query evaluation.

🪶 The $where operator allows you to arbitrarily execute JavaScript expressions during query evaluation.

However, it's important to note that using $where has some important considerations:


Performance : '$where' expressions are executed for each document in the collection, which may be less efficient than using MerlinDB's native query operators.

Security: '$where' expressions can execute any JavaScript code, so it is important to sanitize or validate input to prevent code injection.

Indexing: Using '$where' may prevent the efficient use of indexes in MerlinDB, which may negatively impact query performance.
1
  • import
  • MerlinDB,
  • {
  • Schema
  • }
  • from
  • "@chrisaxxwell/merlin-db";
    2
  • //Or if you are using 'merlindb.max.js' just call 'new MerlinDB()';
  • 3
    4
  • const
  • merlin =
  • new
  • MerlinDB(
  • )
  • ;
    5merlin
  • .connect(
  • "USER-DATABASE"
  • )
  • ;
    6
    7
  • const
  • UserSchema =
  • Schema(
  • {
  •   
    8  
  • name:
  • String
  • ,
    9  
  • age:
  • Number
  • 10
  • }
  • )
  • ;
    11
    12
  • var
  • userModel = merlin
  • .model(
  • "User", UserSchema
  • )
  • ;
    13
    14
  • //userModel.$where(<Function>);  
  • 15userModel.
  • $where(
  • function (
  • )
  • {
  • 16   return (this.age ===
  • 29
  • && this.name !== "Chris"
  • )
  • ;
    17
    18
  • }
  • )
  • .then(
  • e => console
  • .log(
  • e
  • )
  • )
  • ;
    19
    20userModel.
  • $where(
  • function(
  • )
  • {
  • 21   return this.name && this.name.given == "Maya";
    22
  • }
  • )
  • .then(
  • e => console
  • .log(
  • e
  • )
  • )