Mongoose保存到数据库:没有错误

时间:2015-03-31 16:33:21

标签: node.js mongodb mongoose

我基本上坚持本教程(http://mongoosejs.com/docs/index.html),但我既没有得到错误也没有改变我的数据库中的任何内容。

代码:

(function() {
  var configDB, environment, mongoose;

  mongoose = require('mongoose');

  environment = require('../config/config.js')();

  configDB = require('../config/database.js')(environment);

  exports.saveInDatabase = function(books) {
    var db, page, book, test1;
    console.log("start");
    mongoose.connect(configDB.url, {
      auth: {
        authdb: configDB.authdb
      }
    }, function(err) {
      if (err) {
        return console.log(err);
      }
    });
    db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error:'));
    db.once('open', function(callback) {
      return console.log("callback", callback);
    });
    book = require('../models/book.model');
    page = require('../models/page.model');
    test1 = new book({
      "href": "htttp://google.de",
      "title": "test1",
      "pages": [
        {
          "name": "page1"
        }, {
          "name": "page2"
        }
      ]
    });
    test1.save(function(err) {
      if (err) {
        return console.error("err", err);
      }
      return console.log("saved");
    });
    return console.log("done");
  };

}).call(this);

架构book.model.js:

var mongoose = require('mongoose');

// define the schema for book model
var bookSchema = mongoose.Schema({
  href: {
      type: String,
      required: true,
      unique: true
  },
  title: String,
  pages: [{id: mongoose.Schema.Types.ObjectId, name: String}]
});

module.exports = mongoose.model('book', bookSchema);

Schema page.model.js:

var mongoose = require('mongoose');

// define the schema for page model
var pageSchema = mongoose.Schema({
  id: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
    unique: true
  },
  amount: String,
  name: String
});

module.exports = mongoose.model('page', pageSchema);

当记录db时我得到了我的数据库,当记录test1时,我得到了带有自定义id的JSON数组。

{ href: 'htttp://google.de',
  title: 'test1',
  _id: 551acbde9a579f64b70eb44e,
  pages: 
   [ { name: 'page1', _id: 551acbde9a579f64b70eb450 },
     { name: 'page2', _id: 551acbde9a579f64b70eb44f } ] }

1 个答案:

答案 0 :(得分:0)

代码工作,在我的开发服务器上,代码在运行后退出。 mongodb操作是异步的,因此在保存之前该进程被终止。