使用mongoose模型填充集合

时间:2014-03-08 19:36:44

标签: node.js mongodb mongoose

我想知道如何纠正错误以填充app.js中user.js文件中声明的集合用户

user.js文件

    var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    bcrypt = require(bcrypt),
    SALT_WORK_FACTOR = 10;

var UserSchema = new Schema({
    username: { 
        type: String, 
        required: true, 
        index: { unique: true } 
    }

});

module.exports = mongoose.model('User',UserSchema);

app.js文件

 var mongoose = require('mongoose');
require('./models/user');
mongoose.connect('mongodb://localhost/vip');

var models = require('mongoose-models');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {


    var User = models.require('User')();


    var fluffy = new User({ name: 'Eduardo' });


    fluffy.save(function (err, fluffy) {
      if (err) return console.error(err);
      console.log(User);
    });

    User.find(function (err, fluffy) {
      if (err) return console.error(err);
      console.log(User)
    })

});

MongoDB给我的输出错误

C:\ Users \ edu \ Dropbox \ Node.js MongoDB \ Mongoose> node app.js

assert.js:92
  throw new assert.AssertionError({
        ^
AssertionError: path must be a string
    at Module.require (module.js:362:3)
    at require (module.js:380:17)
    at Object.<anonymous> (C:\Users\edu\Dropbox\Node.js MongoDB\Mongoose\models\user.js:5:14)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (C:\Users\edu\Dropbox\Node.js MongoDB\Mongoose\app.js:2:1)

1 个答案:

答案 0 :(得分:1)

您的要求声明(bcrypt)不正确。 require需要一个String,所以你需要把它放在一个引号中。它应该是bcrypt = require('bcrypt')