Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Build a REST API With Express Modeling Data for the API Connecting Mongoose to MongoDB

Brian Patterson
Brian Patterson
19,588 Points

Not sure why this hasn't saved

Not sure why this has not saved!

'use strict';

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/sandbox');

var db = mongoose.connection;

db.on('error', function(err) {
  console.error('connection error', err);
});

db.once('open', function() {
  console.log('db connection successful');
  //All database communication goes here.
  var Schema = mongoose.Schema;
  var AnimalSchema = new Schema({
    type: String,
    size: String,
    color: String,
    mass: Number,
    name: String
  });
  var Animal = mongoose.model('Animal', AnimalSchema);
  var elephant = new Animal({
    type: 'elephant',
    size: 'big',
    color: 'gray',
    mass: 6000,
    name: 'Lawrence'
  });

  elephant.save(function(err) {
    if (err) console.err('Save failed', err);
    else console.log('Saved');
    db.close(function() {
      console.log('db connection closed');
    });
  });
});
Adam Beer
Adam Beer
11,314 Points

Hi Brian! This is the good code. I don't understand what's happend. What does the console write? Maybe try to start the mongod, then in the next step type node mongoose_sandbox.js in an other cmd and finally mongo to connect to the server

1 Answer

Have you started Mongodb in a different console before trying to execute the code? I ran into this problem myself. I kept getting errors and the error message that it wasn't saving. The teacher didn't say to start the MongoDB or if they did I missed it...and I kept trying to figure out what was wrong. Turns out that was all it was. Easy to miss mistake in my case.