Vijay PD
Vijay PD

Reputation: 113

Mongoose find not returning the full collection

I am trying to read data from an html form through a POST, store it in a mongoDB and query it using model.find() and print it in console. But when i run this for the first time the find() is returning an empty object and on giving the next input the previous data excluding the current input is retrieved by th find(). How can i print the full collection including the freshly entered data

 app.post("/", function(req, res){
      postTitle = req.body.postTitle;
      postDesc = req.body.postDesc;
      const post = new Post({
        title:postTitle,
        desc:postDesc
      });
      post.save();

      Post.find({}, function(err, data){
        if(err){
          console.log(err);
        }else{
          console.log(data);
        }
      });
      //console.log(postTitle, postDesc);
    });

Upvotes: 2

Views: 880

Answers (3)

Dara Vichit
Dara Vichit

Reputation: 620

You can try with exec

Post.find({}).exec(function (err, d) {
    if(err){
      console.log(err);
    }else{
      console.log(d);
    }
});

Or try to use async await to make sure your query is running step by step

const user_info = await Post.find({});

This code is not tested

Upvotes: 1

Anurag
Anurag

Reputation: 1

here post.save() is an async function that means it does not complete immediately. You need to use async - await in order to wait for the save() function to finish and then you query the database.

Upvotes: 0

Jonathan Nielsen
Jonathan Nielsen

Reputation: 1502

The command post.save(); will just begin working and your code will continue meanwhile. When your Post.find({} ... starts working, your post.save(); haven't finished working, and thus you're not getting the results.

Change the function so you wait for the save to give you a callback with an ok and then you can query the database.

app.post("/", function(req, res) {
    const postTitle = req.body.postTitle;
    const postDesc = req.body.postDesc;
    const post = new Post({
        title: postTitle,
        desc: postDesc
    });

    post.save(function(err) {
        if (err) {
            // Something went wrong with the save, log and return the error message
            console.error(err);
            return res.send(err);
        }

        console.log(`Post "${postTitle}" saved to database.`);

        // Since we know that the post has been saved, continue querying the database.
        Post.find({}, function(err, data) {
            if (err) {
                // Something went wrong with the query, log and return the error message
                console.error(err);
                return res.send(err);
            }

            console.log(data);
            res.send(data);
        });

    });
});

This code is not tested.

You can also try async/await out, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function and also mongoose documentation for promises & async/await https://mongoosejs.com/docs/promises.html.

I myself would write the function like this using async/await and es6.

app.post('/', async(req, res) => {
    const post = new Post({
        title: req.body.postTitle,
        desc: req.body.postDesc
    });

    try {
        await post.save();
        const posts = await Post.find();
        console.log(posts);
    } catch (err) {
        console.error(err);
    }

    res.end();
});

Upvotes: 2

Related Questions