0

I created a keystone.js folder using Yeoman. In file keystone.js, I add a some code right before keystone.start() to add an new item and list all current items like this:

var newPost = new Post.model({
    title: 'New Post'
});

newPost.save(function(err) {
    // post has been saved      
});

Post.model.find(function (err, posts) {
  if (err) return console.error(err);
  console.log(posts);    
})
keystone.start();

However, the posts in Post.model.find is an empty array, which means there was no item added. Can anyone help me out? Thank you in advance.

Mr Cold
  • 1,565
  • 2
  • 19
  • 29

1 Answers1

3

newPost.save method is async execute.
As in your code, your are query Posts before newPost was successfully saved.

newPost.save(function(err) {
    Post.model.find(function (err, posts) {
        if (err) return console.error(err);
        console.log(posts);
        keystone.start();
    });
});

You code should write like that.

greenlikeorange
  • 505
  • 3
  • 10
  • In this case I think is better to use promises (details [here](http://keystonejs.com/docs/database/)) because the code becomes more readable. Anyway probably you are right in your answer and I upvoted. – danilodeveloper Jul 29 '15 at 14:30