简体   繁体   中英

MY MONGOOSE MODEL IS NOT SAVING IN MY MONGOSH DATABASE

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' });

这是我在 mongosh 中得到的

这是我访问节点中的对象

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%20programming%20is%20a%20technique,is%20presented%20with%20the%20result .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM