Sid
Sid

Reputation: 147

mongoose returns empty array (i tried whatever i could)

Schema: File name: Login.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const LoginSchema = new Schema({
  uname: {
    type: String,
    required: true
  },
  pass: {
    type: String,
    required: true
  }
});

module.exports = Login = mongoose.model('login', LoginSchema);

index.js file:

const express = require('express');
const mongoose = require('mongoose');

const app = express();

// Connect to MongoDB
mongoose
  .connect(
    'mongodb://mongo:27017/docker-node-mongo',
    { useNewUrlParser: true }
  )
  .then(() => console.log('MongoDB Connected'))
  .catch(err => console.log(err));
  
const Login = require('./models/Login');

app.post('/',(req,res) => {
    
    
        const newLogin = new Login({
            uname: req.body.uname,
            pass: req.body.pass
          });
        console.log(newLogin);
        newLogin.save();

    Login.find({},function (err, logins) {
        if (err) return console.error(err);
        console.log("cool: ",logins);
      });
    res.redirect('/main');
});

Heres the output in the console: MongoDB Connected

{ _id: 5fab21a3931694001290326e, uname: 'guest', pass: 'guest' }

cool: []


The output of .find() is empty. AND just before I have put in an entry and that entry even shows in the console. I saw the plural thing and its not working.

Please help.

Upvotes: 0

Views: 88

Answers (1)

Juha Kangas
Juha Kangas

Reputation: 788

Mongodb save() is asynchronous so it doesn't wait for the saving of the document. When it tries to find the document it can't be found it because it hasn't been saved yet. You can use async/await so it waits for the saving process and then proceeds.

app.post('/', async (req,res) => {
        
            const newLogin = new Login({
                uname: req.body.uname,
                pass: req.body.pass
              });
            console.log(newLogin);
            await newLogin.save();
    
        Login.find({},function (err, logins) {
            if (err) return console.error(err);
            console.log("cool: ",logins);
          });
        res.redirect('/main');
    });

Upvotes: 2

Related Questions