gpt4 book ai didi

node.js - 引用 Mongoose 模式的类型错误

转载 作者:IT老高 更新时间:2023-10-28 23:23:41 26 4
gpt4 key购买 nike

我正在使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com