Home > database >  MY MONGOOSE MODEL IS NOT SAVING IN MY MONGOSH DATABASE
MY MONGOOSE MODEL IS NOT SAVING IN MY MONGOSH DATABASE

Time:12-16

Hello I am NEW to this and I am trying to save the Amadeus object I created into mongosh using the method .save() When I connect to my file through node I can see the Amadeus object and edit but when I do amadeus.save() and then go and check my db in mongosh the only thing that appear is moviesApp and is empty. What am I missing?

my JS is

const mongoose = require('mongoose');
mongoose.set('strictQuery', true);
mongoose.connect('mongodb://127.0.0.1:27017/moviesApp', { useNewUrlParser: true, 
useUnifiedTopology: true })
.then(() => {
    console.log("connection open")
})
.catch(err => {
    console.log("oh no error")
    console.log(err)
});
const movieSchema = new mongoose.Schema({
title: String,
year: Number,
score: Number,
rating: String
})
const Movie = mongoose.model('Movie', movieSchema);
const amadeus = new Movie({ title: 'amadeus', year: 1986, score: 9.5, rating: 'R' });

here is what I get in mongosh

here is me accessing the object in node

CodePudding user response:

Your problem is related to how node.js works. You need to understand first how async programming works in node.js.

In your example, the method save only works inside the .then, because in this moment the connection has already done. To fix your problem you can follow it:

const mongoose = require('mongoose');
const movieSchema = new mongoose.Schema({
    title: String,
    year: Number,
    score: Number,
    rating: String
})
const Movie = mongoose.model('Movie', movieSchema);
const amadeus = new Movie({ title: 'amadeus', year: 1986, score: 9.5, rating: 'R' });
mongoose.set('strictQuery', true);
mongoose.connect('mongodb://127.0.0.1:27017/moviesApp', {
    useNewUrlParser: true,
    useUnifiedTopology: true
})
    .then(() => {
        amadeus.save((err) => {
            if (err) {
                console.log(err);
            } else {
                console.log('Amadeus saved!');
            }
        });

    })
    .catch(err => {
        console.log("oh no error")
        console.log(err)
    });

Try to follow this tutorial to understand more about: https://rahmanfadhil.com/express-rest-api/

Try to understand more how async programming works: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing#:~:text=Asynchronous programming is a technique,is presented with the result.

  • Related