简体   繁体   English

expressjs,猫鼬,架构错误

[英]expressjs, mongoose, Schema error

So. 所以。 I'm attempting to use mongoDB with an expressjs project using mongoose, and I get this error. 我试图将mongoDB与使用mongoose的expressjs项目一起使用,但出现此错误。

throw new mongoose.Error.MissingSchemaError(name);
        ^
MissingSchemaError: Schema hasn't been registered for model "device".

I am also new here but here is my source code for index.js where I am getting the error for var device 我在这里也是新手,但是这是我的index.js源代码,其中我得到了var设备的错误

var mongoose = require('mongoose');
var device = mongoose.model('device', device);

/* GET */
router.get('/', function(req, res) {
    new device({
        device_id    : "Something happened"
      }).save( function( err, device, count ){
        res.redirect( '/' );
    });     
});

here is the code I have in app.js: 这是我在app.js中的代码:

//mongo start
var mongo = require('mongodb');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var device = new Schema({
    device_id : String
});

var device = mongoose.model('device', device);

var db = mongoose.connect('mongodb://127.0.0.1:27017/database');

mongoose.connection.once('connected', function() {
    console.log("Connected to database")
});
//mongo end

You need to pass in the schema to the .model-call, not the model. 您需要将架构传递给.model-call,而不是模型。 In your case it looks like you are redeclaring 'device' to contain a model. 就您而言,您似乎在重新声明“设备”以包含模型。

I would also (as a sidenote) encourage you to put this schema in a separate file and export the Schema. 我也(作为一个旁注)鼓励您将该模式放在单独的文件中并导出该模式。

See the mongoose tutorial for an example: mongoose schemas . 有关示例,请参见猫鼬教程: mongoose schemas

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM