类型错误:无法读取未定义的属性“Symbol(mongoose#Document#scope)”
此错误:
collection
是保留的架构路径名,可能会破坏某些功能。您可以使用它,但使用风险自负。要禁用此警告,请将
supressReservedKeysWarning
作为架构选项传递。
/Users/sama/Desktop/spbackend/node_modules/mongoose/lib/helpers/document/compile.js:174
this.$set.call(this.$__[scopeSymbol] || this, path, v);
^
TypeError:无法读取未定义的属性“Symbol(mongoose#Document#scope)” 在 Model.set [as collection] (/Users/sama/Desktop/spbackend/node_modules/mongoose/lib/helpers/document/compile.js:174:32) 在 Function.compile (/Users/sama/Desktop/spbackend/node_modules/mongoose/lib/model.js:4801:30) 在 Mongoose._model (/Users/sama/Desktop/spbackend/node_modules/mongoose/lib/index.js:551:27) 在 Mongoose.model (/Users/sama/Desktop/spbackend/node_modules/mongoose/lib/index.js:509:27) 在 Object. (/Users/sama/Desktop/spbackend/models/product.js:68:28) 在 Module._compile (internal/modules/cjs/loader.js:1063:30) 在 Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10) 在 Module.load (internal/modules/cjs/loader.js:928:32) 在 Function.Module._load (internal/modules/cjs/loader.js:769:14) 在 Module.require (internal/modules/cjs/loader.js:952:19) [nodemon] 应用程序崩溃 - 正在等待文件更改后再启动...
在产品模型中:
const mongoose = require('mongoose');
const productSchema = mongoose.Schema({
name: {
type: String,
required: true
},
description: {
type: String,
required: true
},
richDescription: {
type: String,
default: ''
},
image: {
type: String,
default: ''
},
images: [{
type: String,
}],
brand: {
type: String,
default: ''
},
price: {
type: Number,
default: 0
},
countInStock: {
type: Number,
required: true,
min: 0,
max: 255
},
rating: {
type: Number,
default: 0
},
numReviews: {
type: Number,
default: 0
},
isFeatured: {
type: Boolean,
default: false
},
dateCreated: {
type: Date,
default: Date.now
},
collection: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Collection'
}
}
)
productSchema.virtual('id').get(function () {
return this._id.toHexString();
});
productSchema.set('toJSON', {
virtuals: true,
});
exports.Product = mongoose.model('Product', productSchema);
在集合模型中:
const mongoose = require('mongoose');
const collectionSchema = mongoose.Schema({
name: {
type: String,
required: true
},
image: {
type: String,
required: true
}
})
collectionSchema.virtual('id').get(function () {
return this._id.toHexString();
});
collectionSchema.set('toJSON', {
virtuals: true,
});
exports.Collection = mongoose.model('Collection', collectionSchema);
您的问题与架构中的
collection
字段有关,我遇到了同样的问题,花了很长时间才弄清楚。请参阅此处的 mongo 架构保留字段:
https://mongoosejs.com/docs/api.html#schema_Schema.reserved
要修复此问题,只需将字段重命名为其他名称:
collectionName: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Collection'
}
collection
是保留关键字。您可以在此处查看其他保留关键字:
https://mongoosejs.com/docs/api.html#schema_Schema.reserved
您必须将
collection
字段重命名为其他名称。