无法使用Mongoose创建数据库

时间:2016-03-03 00:44:56

标签: node.js mongodb mongoose

我找到了this project, 但由于某种原因,它不会使用localhost:3000/create创建数据库。

这是models.js:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/autocomplete');
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;

// Person schema
var Person = new Schema({
  firstname: {type: String, required: true},
  lastname: {type: String, required: true}
});
mongoose.model('Person', Person);
var Person = exports.Person = mongoose.model('Person');

这是app.js:

var express = require('express'),
sys = require('util'),
app = module.exports = express.createServer(),
models = require('./model'),
Person = models.Person;

var app = module.exports = express.createServer();
var everyone = require("now").initialize(app);

//Configuration
app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(require('stylus').middleware({ src: __dirname + '/public' }));
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); 
});

app.configure('production', function(){
    app.use(express.errorHandler()); 
});

// base url and template
app.get('/', function(req, res){
    res.render('index', {
    title: 'Home'
    });
});

// now js search function
everyone.now.search = function(text, count, callback) {
    // create regex for "contains" and ignore case
    var regex = new RegExp(text.term, 'i');
    // execute the search
    Person.find({firstname: regex}, function(err, docs) {
      var names = [];
      for(var nam in docs) {
          // push the firstname to the array
          names.push(docs[nam].firstname);
      }
      // send back via callback function
      callback(null, names);
  });
};

// function to create our test content...
app.get('/create', function(req, res){
    var person = new Person({firstname: 'Dominic', lastname: 'Böttger'});
    person.save();
    var person2 = new Person({firstname: 'Lorem', lastname: 'Ipsum'});
    person2.save();
    var person3 = new Person({firstname: 'Heinz', lastname: 'Ketchup'});
    person3.save();
    res.redirect('/');
});

app.listen(3000);
console.log("Autocomplete server listening on port %d in %s mode", app.address().port, app.settings.env);

1 个答案:

答案 0 :(得分:1)

使用更多代码测试您的代码,如下所示

person.save(function (err) {
    if (err)
        console.log(err);
    else
        console.log('save person successfully');
});

结果,日志显示save person successfully。即,数据将保存到people db。

下的autocomplete集合中
> use autocomplete
switched to db autocomplete
> db.people.find()
{ "_id" : ObjectId("56d78b9084ae33bc0f0d0c38"), "firstname" : "Dominic", "lastna
me" : "Böttger", "__v" : 0 }