静态不是一个函数 - 猫鼬
我收到错误“product.try() is not a function”
如果我立即调用 try() 它工作正常, 节点识别模型“产品”。
关于猫鼬的工作原理,有什么我不明白的吗? 我在一个文件中运行整个代码,并按照我参加的课程中视频中的导师步骤进行操作。
问题是什么?谢谢。
文件:product.js =>
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/shopApp')
.then(()=>{
console.log('CONNECTION OPEN!!!')
})
.catch(err=>{
console.log('HO NO ERROR!!!')
console.log(err)
})
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true,
maxlength: 20 // Schema options
},
price: {
type: Number,
min: [0, 'Price must be positive']
},
onSale: {
type: Boolean,
default: false
},
categories: {
type: [String]
},
qty: {
online: {
type: Number,
default: 0
},
inStore: {
type: Number,
default: 0
}
},
size: {
type: String,
enum: ['S', 'M', 'L']
}
})
const product = mongoose.model('product', productSchema);
productSchema.statics.try = function(){
console.log('OK')
};
product.try();
I get the error "product.try() is not a function"
If I immediately invoke the try() it works ok,
and node recognize the model "product".
is there something I d'ont understand about how mongoose works?
I run the whole code in the one file and I followed the steps of the tutor from the video in the course I take.
what is the problem? thank you.
file: product.js =>
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/shopApp')
.then(()=>{
console.log('CONNECTION OPEN!!!')
})
.catch(err=>{
console.log('HO NO ERROR!!!')
console.log(err)
})
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true,
maxlength: 20 // Schema options
},
price: {
type: Number,
min: [0, 'Price must be positive']
},
onSale: {
type: Boolean,
default: false
},
categories: {
type: [String]
},
qty: {
online: {
type: Number,
default: 0
},
inStore: {
type: Number,
default: 0
}
},
size: {
type: String,
enum: ['S', 'M', 'L']
}
})
const product = mongoose.model('product', productSchema);
productSchema.statics.try = function(){
console.log('OK')
};
product.try();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您实际上需要在调用
mongoose.model()
之前添加.try
函数,这应该适合您:
文档
You actually need tadd the
.try
function before callingmongoose.model()
This should work for you:
docs