猫鼬,我在哪里定义模型

时间:2014-01-21 23:43:26

标签: node.js mongodb mongoose

我正在构建我的第一个节点/ express / mongoose应用程序。我坚持这个错误:

500 ReferenceError:未定义ServerModel

下面是文件“routes / input.js”。我无法弄清楚我做错了什么,模型在我尝试使用之前已经明确定义了。

exports.verify = function(req, res){
var mongoose = require('mongoose');

var serverSchema = new mongoose.Schema({
  name: { type: String, unique: true },
  os: String,
  osVersion: String,
  createdOn: {type: Date, default: Date.now },
  modifiedOn: Date,
  cores: Number,
  memoryGB: Number,
  licenses: [licenseSchema]
});
var licenseSchema = new mongoose.Schema({
  name: String,
  createdOn: {type: Date, default: Date.now },
  modifiedOn: Date
});

mongoose.model( 'ServerModel', serverSchema );

  var inputVar = new ServerModel({
    name: req.param.name,
    os: req.param.OS,
    osVersion: req.param.OSv
  });
  res.render('input', { title: 'verify' });
};

2 个答案:

答案 0 :(得分:3)

你需要说:

var ServerModel = mongoose.model( 'ServerModel', serverSchema );

答案 1 :(得分:1)

您刚刚开始时的另一个答案:mongoose-simpledb

  

免责声明:我写了它。

  

导致名称字段不在上面的gif中显示的故障实际上是​​用户错误。在测试期间,我插入了具有相同用户名的相同记录,但它没有名称字段。用户的最终检索实际上检索的是该用户而不是第二个用户:/

它允许您在应用程序根目录(或您在选项中指定的任何文件夹)的“dbmodels”文件夹中的单独文件中定义所有模式。示例模型/模式文件如下所示:

// /dbmodels/Book.js

exports.schema = {
    title: String,
    publishDate: Date,
    authorName: {
        first: String
        last: String
    }
};

注意它与mongoose想要的模式完全相同的对象。您还可以在模型文件中定义方法和虚拟属性。这是一个示例虚拟属性,它允许您获取和设置authorName.full属性,即使数据库中存储的文档没有这样的属性:

// /dbmodels/Book.js continued...

exports.virtuals = {
    'authorName.full': {
        get: function () {
            return this.authorName.first + ' ' + this.authorName.last;
        },
        set: function (fullName) {
            if (fullName.indexOf(' ') !== -1) {
                var names = fullName.split(' ');
                this.authorName.first = names[0];
                this.authorName.last = names[1];
            } else {
                this.authorName.first = fullName;
                this.authorName.last = '';
            }
        }
    }
};

一旦您的模型文件设置完毕,您希望它们如何初始化您的数据库非常容易。

// app.js

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

simpledb.init('mongodb://localhost/test', function (err, db) {
    if (err) return console.error(err);
    // Now you can access your models via the db object. Example:
    db.Book.find({ title: "Pale Blue Dot" }, function (err, books) {
        // ...
    });
    // This is a great place to put your application code, such as an
    // express app and then pass the db object wherever you need it :)
});

我编写了这个模块,以便更容易使用Mongoose进行98%的用例。最终,您只需要一个包含所有模型的对象,以便将其用作数据层的API。这个模块完成了所有这些。你需要传递的只是你的连接字符串,你很高兴。但是,您也可以传入选项对象来代替连接字符串,并配置某些内容以满足您的需求(请参阅README)。

如果有帮助的话,我最近还会整理一个Node.js & MongoDB 101视频(没有货币化):)

相关问题