我正在使用mongoose ODM开发一个使用mongodb的节点应用程序。我在类型引用驻留在不同文件中的模式时收到错误。
我在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)
我无法弄清楚错误的原因。如果两个模式都在同一个文件中,则代码运行正常。但是当我在两个不同的文件中分离出模式时,我遇到了错误。我该如何解决这个错误?任何帮助将不胜感激。
答案 0 :(得分:18)
您的userSchema中有拼写错误。你已经把
了trips: [{Type: mongoose.Schema.Types.ObjectId, ref: 'Trip'}]
但它应该是
trips: [{type: mongoose.Schema.Types.ObjectId, ref: 'Trip'}]
Type
应为小写type