You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

1 Días
9 Hrs
33 Min
20 Seg

Limpiar y crear base de datos NoSQL con MongoDB

14/17
Resources

How to create functions to manipulate non-relational databases?

Non-relational databases are essential tools in the modern world of development, especially when working with complex and constantly changing data structures. In this tutorial, I'll show you how to create functions in JavaScript to perform key actions on non-relational databases, using MongoDB as an example. Let's get started!

How to create a new document in MongoDB?

Creating a new document in a database is one of the most common operations, and below I show you how you can do it using an asynchronous function in JavaScript and MongoDB.

async function createPlanet(planet) { const client = await MongoClient.connect(uri, options); const result = await client.db("space").collection("planets").insertOne(planet); console.log(result);}

In this example, the createPlanet function connects to the database and uses the insertOne method to add a new document to the planets collection. It is important to pass the planet object as an argument, since it contains all the information we want to store.

How to test the creation function?

To make sure that the function is working correctly, you can perform some basic tests. You can use automated testing tools, such as Cypress, to validate the operation.

cy.task("createPlanet", planetData).then(result => { expect(result.acknowledged).to.be.true; expect(result).to.have.property("insertedId");});

This fragment executes the createPlanet function and verifies that a new document was successfully inserted by checking that the acknowledged is true and that the insertedId is present.

How to delete documents from a collection?

Removing all documents from a collection is an operation that should be performed with caution. But here is an example of how to do it in MongoDB:

async function clearPlanets() { const client = await MongoClient.connect(uri, options); await client.db("space").collection("planets").deleteMany({}); console.log("All documents deleted.");}

The clearPlanets function connects to the database and deletes all documents in the planets collection using deleteMany with an empty object as a filter, indicating that all documents should be deleted.

How can you implement updates and individual deletion of records?

I suggest you use the following recommendations for your next implementations:

  1. Update function: create a function that receives the document ID and the new data to be updated. It should use methods such as updateOne.

  2. Single record delete function: Develop a function that uses deleteOne along with a filter based on the ID of the document to be deleted.

  3. Handling IDs: Be sure to carefully store and manage IDs, as these will be crucial when performing updates or deletions.

What comes next?

In the following lessons, we will explore how to integrate databases with APIs to ensure that the information you manage on the frontend is consistent with that stored on the server. This knowledge will allow you to validate and ensure that the API and the database work harmoniously. Keep learning and delving deeper into this fascinating world of non-relational databases!

Contributions 2

Questions 2

Sort by:

Want to see more contributions, questions and answers from the community?

¡Rock n’ Roll! 🤟
.
Recuerden que en MongoDB tenemos la siguiente estructura:

  1. Organización
  2. Proyectos
  3. Cloisters
  4. Base de datos
  5. Colecciones
  6. Documentos (registros en DB relaciones)

.
Para efectos de backend para frontend, recomiendo realm de MongoDB para agilizar el desarrollo con no relaciones.

El método **remove ** no me funciona, así tuve que usar el deleteMany pasándole como parámetro un filtro vacio, tal como muestra el profesor.

return await planets.deleteMany({})