我正在使用mongoose ODM使用mongodb开发 Node 应用程序。类型引用驻留在不同文件中的架构时出现错误。

我在user.js文件中有以下代码:

var mongoose = require('mongoose');
var Trip = require('./trip');

var userSchema = mongoose.Schema({
    firstName: String,
    lastName: String,
    salt: String,
    hash: String,
    emailAddress: {
        type: String,
        unique: true
    },
    trips: [{Type: mongoose.Schema.Types.ObjectId, ref: 'Trip'}]
});

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

userSchema具有对tripSchema的类型引用。

我的trip.js文件中的代码是:
    var tripSchema = mongoose.Schema({
      name: String,
      location: String,
      arrivalDate: Date,
      departureDate: Date,
      type: String});

   module.exports = mongoose.model('Trip', tripSchema);

运行应用程序时,出现以下错误:
    /usr/lib/node_modules/mongoose/lib/schema.js:360
    throw new TypeError('Undefined type at `' + path +
          ^
TypeError: Undefined type at `trip.ref`
  Did you try nesting Schemas? You can only nest using refs or arrays.
    at Function.Schema.interpretAsType       (/usr/lib/node_modules/mongoose/lib/schema.js:360:11)
    at Schema.path (/usr/lib/node_modules/mongoose/lib/schema.js:303:29)
    at Schema.add (/usr/lib/node_modules/mongoose/lib/schema.js:217:12)
    at Schema.add (/usr/lib/node_modules/mongoose/lib/schema.js:212:14)
    at new Schema (/usr/lib/node_modules/mongoose/lib/schema.js:73:10)
    at Function.Schema.interpretAsType (/usr/lib/node_modules/mongoose/lib/schema.js:345:44)
    at Schema.path (/usr/lib/node_modules/mongoose/lib/schema.js:303:29)
    at Schema.add (/usr/lib/node_modules/mongoose/lib/schema.js:217:12)
    at new Schema (/usr/lib/node_modules/mongoose/lib/schema.js:73:10)
    at Mongoose.Schema (/usr/lib/node_modules/mongoose/lib/schema.js:53:12)

我无法找出错误原因。如果两个模式都在同一文件中,则代码运行良好。但是,当我在两个不同的文件中分离出架构时,我遇到了错误。如何解决此错误?任何帮助将不胜感激。

最佳答案

您的userSchema中有一个错字。你放了

trips: [{Type: mongoose.Schema.Types.ObjectId, ref: 'Trip'}]

但这应该是
trips: [{type: mongoose.Schema.Types.ObjectId, ref: 'Trip'}]
Type应该是小写的type

关于node.js - 类型引用 Mongoose 模式时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21425382/

10-11 07:23