Model Methods: Find And Modify

Finding and modifying a document at the same time in the database collection in MerlinDB.

🪶 The findAndModify method is a method that does two things at the same time: finds a document and modifies (or removes) it.

It has 7 properties, they are:

query {Object} (Required): Filters what you are looking for;

options {Object}: The query options;

field {Object}: The fields you want to return.

remove {Boolean} (Required or update): If set to true removes the document;

update {Object} (Required or remove): Defines the changes to be applied;

upsert {Boolean}: If set to true allows inserting a new document if no document corresponding to the search criteria is found;

new {Booelan}: If set to true, returns the updated document instead of the original.
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.findAndModify(
  • 15
  • //   <query>,
  • 16
  • //   <options>,
  • 17
  • //   <new>,
  • 18
  • //   <fields>,
  • 19
  • //   <remove>,
  • 20
  • //   <update>,
  • 21
  • //   <upsert: true
  • 22
  • //);
  • 23
    24userModel
  • .findAndModify(
  • {
  • 25  
  • query:
  • {
  • name:
  • {
  • $regex:
  • "Marley "
  • }
  • }
  • ,
    26  
  • new:
  • true
  • ,
    27  
  • fields:
  • {
  • name:
  • 1
  • ,
  • age:
  • 1
  • }
  • ,
    28  
  • remove:
  • false
  • ,
    29  
  • update:
  • {
  • 30      
  • $inc:
  • {
  • age:
  • 1
  • }
  • ,
    31      
  • //Increases +1 in age
  • 32      
  • $set:
  • {
  • name:
  • "Marley Axxwell"
  • }
  • 33      
  • //Change name to Marley Axxxell
  • 34  
  • }
  • ,
    35  
  • upsert:
  • true
  • 36
  • }
  • )
  • .then(
  • e => console
  • .log(
  • e
  • )
  • )
  • ;