pekkav
pekkav

Reputation: 133

Mongoose silently fails database write

I'm trying to write a simple web app with node.js, Express and MongoDB. I followed the instructions on the Mongoose documentation, but my code seems to fail silently when I'm trying to write to the DB.

I include the following code in my main app.js -file with var db = require("./db"):

// db.js

var mongoose = require('mongoose');

var Schema = mongoose.Schema
  , ObjectId = Schema.ObjectId;

var server_name = "localhost";
var db_name = "database";

var db = mongoose.connect('mongodb://'+server_name+'/'+db_name);
log.debug('Connecting to MongoDB "'+db_name+'" at '+server_name);

// Database schemas

var Compo = new Schema({
  name : String,
  description : String
});

var compoModel = mongoose.model('Compo', Compo);

var compoModelInstance = new compoModel();
compoModelInstance.name = "Competition name.";
compoModelInstance.description = "Competition description.";

compoModelInstance.save(function (err) {
  if (err !== null) {
    console.log(err);
  } else {
    console.log("Save successful.");
  }
});

The connection is created successfully, since it shows up in the mongod console output. The program also prints out "Save successful.", but when I inspect the situation from the mongo shell with db.database.find(); I can see the database is still empty.

Why isn't the object saved?

Upvotes: 0

Views: 1223

Answers (1)

mpobrien
mpobrien

Reputation: 4962

I tried your code and it works fine for me. Are you looking in the right place for your data?

Connect with your mongo shell and try the following:

use database;
db.compos.find()

Upvotes: 2

Related Questions