0

I am a beginner in Backend developing, and I have this array called (Movie). I use expressJS and I want to save the array on MongoDB.I will use Mongodb atlas for my database. I appreciate your help

I tried to follow this instruction on this website:
https://medium.com/@lavitr01051977/node-express-js-aea19636a500

I ignored the first steps and starts from ( Connecting to the Database ) title but It doesn't work.

var express = require('express')
var app = express()

app.get('/', (req, res) => {
    res.send('ok')
});
//movie array
const movies = [
    { title: 'Jaws', year: 1975, rating: 8 },
    { title: 'Avatar', year: 2009, rating: 7.8 },
    { title: 'Brazil', year: 1985, rating: 8 },
    { title: 'الإرهاب والكباب‎', year: 1992, rating: 6.2 }
]
//read the array movie
app.get('/movies/read/',(req,res) => {
    res.send({status:200, data:movies})
})
//add elements to array movies
app.get('/movies/add',(req,res) => {
    var t = req.query.title
    var y = req.query.year
    var r = req.query.rating
    if(t == undefined || y == undefined || y.length > 4 || isNaN(y)) {
        res.send({status:403, error:true, message:'you cannot create a movie without providing a title and a year'})
    }
    if (r == "") {
        r = 4
    }
    movies.push({title: t, year: y, rating: r})
        res.send({status:200, data:movies})
    })
//delete elements from array movies
app.get('/movies/delete/:ID',(req,res) => {
    var d = req.params.ID
    if (d > 0 && d < movies.length ) {
        movies.splice(d-1, 1)
        res.send({status:200, message: movies})
    }
    else {
        res.send({status:404, error:true, message:'the movie <ID> does not exist'})
    }
    })      
//update elements from array movies
app.get('/movies/update/:ID',(req,res) => {
    let c = req.params.ID
    let x = req.query.title
    let y = req.query.year
    let z = req.query.rating

    function update(a, b) {
        if(a != undefined || a == "") {
            movies[c-1][b] = a
        }
    }

    if(c > 0 && c < movies.length ) {
        update(x, 'title')
        update(y, 'year')
        update(z, 'rating')
        res.send({status:200, message: movies})
    }
    else {
        res.send({status:404, error:true, message:'the movie <ID> does not exist'})
    }
})

app.listen(3000, () => console.log('listinig on port 3000'))

I expect the answer is like the link that I put it above on medium.com website

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
Rida
  • 51
  • 10
  • where is your schema ? – Nikhil Savaliya Jun 13 '19 at 15:16
  • The code you are showing doesn't deal with any database at all. Consider rewriting your question by adding the part where you are attempting to work with the database and logs/messages on what exactly is failing. – Anton Jun 13 '19 at 15:23

3 Answers3

2

mongoose is a framework that facilitates interacting with MongoDB. Actually you basically never want to do all the validation, casting, and logic boilerplate on your own, so why reinvent the wheel.
And since you're a beginner, don't be afraid of frameworks. There are many useful frameworks for many areas of backend and frontend to make life easier for you.

The article you shared is self-explanatory, but I will sum up only the database part for you (I won't go deep into your code, no donkey work. the rest is up to you):

1) First of all install mongoose.

npm install mongoose

The article has --save which is no need to add anymore, as "npm install saves any specified packages into dependencies by default."(ref.)

2) to able to access and use mongoose, you need to import it, in node way, that is require().

const express = require(‘express’)
const mongoose = require(“mongoose”);
const bodyParser = require(‘body-parser’);  

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); 

And what's body-parser there for?
When dealing with database in express, you'll sooner or later come across errors like this one.
and the reason why we need one after all is best explained in this answer.
Also, recent versions of express has its own body parser now, so you can use app.use(express.json()) instead of app.use(bodyParser.json()).
Important: body-parser must be before your routes.

3) use mongoose.connect(url).

url argument is what you find in your MongoDB Atlas. :

Location: clusters tab -> connect -> connect your application -> driver node.js

Which gives you, something like this:

mongodb+srv://<user>:<password>@,cluster>.mongodb.net/test?retryWrites=true&w=majority

Important: you use user and password of the user you made within Database Access tab, not your own user and password.

You can set up your environment variables to secure sensitive and changeable data. But I prefer using config.js for simplicity, and which usually resides in the root of app.

Not only you can secure them (like for using .gitignore), but also easily modify them as there are variables that might change from one environment to another environment, making them available in one place and easy to find, instead of looking for them to change all over your app.

For .env file approach, read this article.

Important: in case you want to put your code in github or anywhere online, which one reason we use config.js, don't forget to add this file in .gitignore to avoid such sensitive data get leaked and exposed to others online.

in config.js you can do so:

exports.username = 'your user';
exports.pass = 'your pass';
exports.myCluster = 'your cluster's name';

Then import them so:

const { username, pass, myCluster } = require('./config'); <- the path might be different for you!

Tip: You can use back-tick (` `) to easily insert those variables for const url, through interpolation.

That is:

const url = `mongodb+srv://${username}:${password},${myCluster}.mongodb.net/test?retryWrites=true&w=majority`

Important: make sure to whitelist your IP from MongoDB side (atlas), otherwise you will get connection error. Under security: Network Access -> IP Whitelist
You could use 0.0.0.0/0 to whitelist all IPs.
Also, when using VPN, your IP will change too.

4) last but not least, after connecting to database, you need to define your schema:

const moviesSchema = new mongoose.Schema({
title: String,
year: Number,
rating: Number
});

And

const Movies = mongoose.model(“Movies”, moviesSchema);

Tip: A common mistake many newbies make is that they forgot to use new:
new mongoose.Schema({...})

If you want to create your model in a separate file (which is the best practice), you will need to modify your const Movies so:

module.exports = mongoose.model(“Movies”, moviesSchema);

Don't forgot to add const mongoose = require('mongoose'); in that separate js model file.

And in wherever you use want to use this model, you import so:

const Movies= require('../models/movies'); (the path may different for your app)

The rest, my friend, is up to you. What you want to do with your database and how to use it.

Note to others: I put so much time and mind to this as I was writing this. Please, if you see something wrong, or think you can add something, feel free to edit and improve my answer.

Matin Sasan
  • 1,835
  • 1
  • 13
  • 26
0

I would suggest you to take look at mongoose framework to interact with a Mongo database using NodeJS.

However, in the code you've provided you're not interacting with any database. You would need to define a Schema and then you could save a new doc or do any other action with your collection. Please follow some 'Get started' guide on how to do it.

Hope it helps!

Alvaro
  • 1,853
  • 18
  • 24
0

I ll explain step by step. NOTE THAT THIS PROCESS SHOULD BE RUN ONLY ONCE. SO YOU SHOULD ADD THIS CODE TO A SEPARATE MODULE AND RUN IT ONCE. otherwise you will keep adding more items to the db. lets name this module

movies.js

//you need to connect to mongodb through mongoose. 

const mongoose = require("mongoose");
mongoose
  .connect("mongodb://127.0.0.1:27017/movies", { //will create movies db automatically
    useNewUrlParser: true,
    useCreateIndex: true
  })
  .catch(err => {
    console.log(err.message);
    process.exit(1);
  })
  .then(() => {
    console.log("connected");
  });

//next create a schema and model:

const movieSchema = new mongoose.Schema({
  title: String,
  year: Number,
  rating: Number
});
const Movie = mongoose.model("Movie", movieSchema);

//create movies array based on `Movie model` so u can use save() method.

const movies = [
  new Movie({ title: "Jaws", year: 1975, rating: 8 }),
  new Movie({ title: "Avatar", year: 2009, rating: 7.8 }),
  new Movie({ title: "Brazil", year: 1985, rating: 8 }),
  new Movie({ title: "الإرهاب والكباب‎", year: 1992, rating: 6.2 })
];

//Last step save it.

movies.map(async (p, index) => {
  await p.save((err, result) => {
    if (index === movies.length - 1) {
      console.log("DONE!");
      mongoose.disconnect();
    }
  });
});

map is an array method.it iterates over array and save each item inside the array. Once every item in the array is saved we need to disconnect from db. array method takes 2 arguments. on is each item inside the array, second one is the index of each item. index in array starts from 0, so last item's index in movies array is 3 but length of the array is 4 so once 4-1=3 that means we saved every item in the array.

Now run the code

node movies.js
Yilmaz
  • 35,338
  • 10
  • 157
  • 202