Saving Documents
When saying saving
, it means creating
, updating
or replacing
documents, let's see how to do that.
Create new document
To create a new document, use the create
method:
import { query } from "@mongez/monpulse";
const user = await query.create("users", {
name: "John Doe",
isActive: true,
});
This will create a new document in the users
collection, and return the created document.
Create multiple documents
To create multiple documents, use the createMany
method:
import { query } from "@mongez/monpulse";
const users = await query.createMany("users", [
{
name: "John Doe",
isActive: true,
},
{
name: "Jane Doe",
isActive: false,
},
]);
This will create two documents in the users
collection, and return the created documents with _id
field with each document.
Update document
To update a document, use the update
method:
import { query } from "@mongez/monpulse";
const user = await query.update(
"users",
{
id: 5123123,
},
{
isActive: false,
}
);
This will update the document with the given id
and return the updated document.
Update multiple documents
To update multiple documents, use the updateMany
method:
[
{ "_id": 1, "name": "John", "age": 25 },
{ "_id": 2, "name": "Alice", "age": 30 },
{ "_id": 3, "name": "Bob", "age": 35 },
{ "_id": 4, "name": "Emily", "age": 28 }
]
import { query } from "@mongez/monpulse";
const users = await query.updateMany(
"users",
{ age: { $gt: 25 } }, // Filter: Users with age greater than 25
{ $set: { age: 40 } } // Update: Set the age to 40
);
This will update all users with age greater than 25, and set their age to 40.
Replace document
To replace a document, use the replace
method:
import { query } from "@mongez/monpulse";
const user = await query.replace(
"users",
{
id: 5123123,
},
{
name: "John Doe",
isActive: false,
}
);
Please be aware that this will replace the whole document with the given data, and will remove any other fields that are not included in the given data.
Upsert document
To upsert a document, use the upsert
method:
import { query } from "@mongez/monpulse";
const user = await query.upsert(
"users",
{
id: 5123123,
},
{
name: "John Doe",
isActive: false,
}
);
This will update the document with the given id
if it exists, otherwise it will create a new document with the given data.