Node.JS Express 4 - Mongoose Does not saving data Node.JS Express 4 - Mongoose Does not saving data mongoose mongoose

Node.JS Express 4 - Mongoose Does not saving data


The .create() function is a shortcut for new Model and .save(). You are trying to .create an instance of Model rather than a simple Object. See Constructing documents in Mongoose's Models documentation for their quick example.

The return from a Mongoose data function is just the promise of an asynchronous task to be run in the future, logging that is largely pointless. Use .then() to wait until the promise has been resolved.

Error handling is missing from your code as well, something could be getting thrown there. Use a .catch() for promise error handling.

Post.create({ created_by: ""+Math.random() }).then(function (result) {  console.log('Saved' result)}).catch(function (err) {  console.error('Oh No', err)})

All of this can be done with callbacks (like the Mongoose docco examples) but promises, particularly bluebird promises are nicer.


I just use this syntax combination to create and save my model:

var myPage = new LandingPage({  user:req.user,  slug: req.body.slug,}).save(function(err,savedModel){  if(!err){    console.log(savedModel);  }});


You are calling the wrong model in your app.js module as you are importing the model as

var Post_Data = require("./models/post"); // <-- Post_Data model never used........

but creating a new Post model instance in your router implementation as

var Post = mongoose.model("Post"); // <-- different modelvar post    =   new Post({                        created_by: ""+Math.random()                    });

You need to call and use the correct models. So I would suggest you re-write your app.js module to use the save() method as:

var Post = require("./models/post"); // <-- import correct Post model........router.get('/', function(req, res, next) {    var post = new Post({ created_by: ""+Math.random() });    post.save().then(function(post) {        console.log(post); // <-- newly created post        res.render('index', {            title: 'Express',            site_name: 'Our Site',            layout: 'templates/layout'        });    })    .catch(function(err) {        console.error('Oopsy', err);    });});