How Create Relationships with Mongoose and Node.js ( with real example )
Tags: node, mongodb, javascript, nosql
Published: 2019-10-20 14:27:31

---
title: How Create Relationships with Mongoose and Node.js ( with real example )
published: true
description: create relationships with mongoose and node.js
tags: #node #mongo #javascript #nosql
cover_image : https://thepracticaldev.s3.amazonaws.com/i/bccfxptwdssjo6faabnq.png
---
Before all, **not exists** JOIN here! Basically is saved the **``_id``** from one collection to another collection ( **``{type: mongoose.Schema.Types.ObjectId,ref:'NameOfSchema'}``**).Where the data related it select with the **``populate()``** method.

**The ideia of the example**
Will be a system that allows **``Users``** to register and that these users can create **``Posts``**

**required dependencies**
```javascript
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mongoose": "^5.7.5",
    "nodemon": "^1.19.4"
```

**Project Structure**
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/vlavlgtndxrstassvfxp.png)

├── index.js 

```javascript
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();

// middlewares
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
mongoose.connect('mongodb://localhost:27017/relationships',{
    useNewUrlParser: true,
    useUnifiedTopology: true 
})

// routes
app.use(require('./app/routes'));

app.listen(3000, () => console.log('server on!'));

```

├── models
└── user.js

```javascript
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
    name :{
        type:String,
        required: '{PATH} is required!'
    },
    bio: {
        type:String
    },
    website:{
        type:String
    },
    posts : [
        {type: mongoose.Schema.Types.ObjectId,ref:'Post'}
    ]
},{
    timestamps: true
})

module.exports = mongoose.model('User',UserSchema);

```
├── models
└── post.js

```javascript
const mongoose  = require('mongoose');
const PostSchema = new mongoose.Schema({
    title:{
        type:String,
        required: '{PATH} is required!'
    },
    subtitle :{
        type: String
    },
    user :{
        type:mongoose.Schema.Types.ObjectId,
        ref:'User'
    }
},{
    timestamps:true
})

module.exports = mongoose.model('Post',PostSchema);
```
└── user.js ( controller )

```javascript
const User = require('../../models/user');

module.exports = {
    create : async (req, res) =>{
        const { name, bio, website } = req.body;
        const user = await User.create({
            name,
            bio,
            website
        })

        return res.send(user)
    },

    find : async (req, res) => {
        const user = await User.find()
        return res.send(user)
    },
    postsByUser : async (req, res) => {
       const { id } = req.params;
       const user = await User.findById(id).populate('posts');
        
        res.send(user.posts);
    }
}

```

notice that   **``const user = await User.findById(id).populate('posts')``** is equivalent to : 

```javascript
 user.posts.forEach(async element => {
           const post = await Post.findById(element);
              console.log(post);
        });
```

└── post.js ( controller )

```javascript 
const Post = require('../../models/post');
const User = require('../../models/user');

module.exports = {
    create : async (req, res) => {
        
        console.log(req.params);
        user = req.params;
        id = user.id;
        const { title, subtitle} = req.body;
        const post = await Post.create({
            title,
            subtitle,
            user:id
        });
        await post.save();

        const userById = await User.findById(id);
        
        userById.posts.push(post);
        await userById.save();

        return res.send(userById);
    },
    userByPost : async (req,res)=>{
        const { id } = req.params;
        const userByPost = await Post.findById(id).populate('user');
        res.send(userByPost);
    }
}
```
└── routes.js 

```javascript
const express = require('express');
const router = new express.Router;
const User = require('./controllers/user/user');
const Post = require('./controllers/post/post');
router.get('/',(req,res)=>res.send('ok'));
// user routes
router.post('/user/create',User.create);
router.post('/user/find',User.find);
router.post('/user/find/post/:id', User.postsByUser);
// post routes
router.post('/post/create/:id', Post.create);
router.post('/post/populate/:id',Post.userByPost);

module.exports = router;
```
**configure** └── package.json
to use nodemon in your project, set  "start" key in "scripts",passing the nodemon command and the application root filename.


```bash
"scripts": {
    "start": "nodemon index.js"
  },
```
after this, run command "npm start" in your terminal and the application will restart the server every time any files of your project are changed, making development more productive.

**Final Result**

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/ilf1s5axkxgye5k475k4.gif)

**``thanks for everything!``** :smile: