# Databases

Node.js permet d'utiliser facilement toutes sortes de *databases* : SQL, NoSQL etc...

<https://github.com/felixge/node-mysql>

{% embed url="<https://github.com/felixge/node-mysql>" %}

<https://github.com/mongodb/node-mongodb-native>

{% embed url="<https://github.com/mongodb/node-mongodb-native>" %}

Pour la plupart des applications, il est préférable d'utiliser une base NoSQL telle que MongoDB pour bénéficier des avantages suivants :

* L'absence de schéma statique permet de s'adapter rapidement aux nouveaux besoins.
* La *scalability* grâce au *sharding*.
* Syntaxe simplifiée.
* Map/Reduce.
* ...

## ORM (Object-Relational Mapping) / ODM (Object-Document Mapping)

Comme dans les autres langages, il est fortement recommandé d'utiliser une couche d'abstraction pour des raisons de factorisation, simplification et sécurité.

### ORM SQL

<http://sequelizejs.com>

{% embed url="<http://sequelizejs.com>" %}

```javascript
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password');

const User = sequelize.define('User', {
  firstName: Sequelize.STRING,
  lastName: Sequelize.STRING
});

const main = async () => {

    await sequelize.sync();
    
    const userModel = await User.create({firstName: 'Foo', lastName: 'BAR'});

    const user = user.get({plain: true})

};

main();
```

### ODM MongoDB

<http://mongoosejs.com/>

{% embed url="<http://mongoosejs.com/>" %}

```javascript
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/test');

const User = mongoose.model('User', {
    firstName: String,
    lastName: String
});

const foo = new User({
    firstName: 'Foo',
    lastName: 'BAR'
});

await foo.save();
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://guide-node-js.wishtack.io/databases.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
