【发布时间】:2017-12-16 08:47:38
【问题描述】:
这种情况很少发生,但令人压力。
我得到了这个架构和模型:
//Product Schema
let ProductSchema = new Schema({
name: {
type: String,
required: true
},
description: {
type: String
},
price: {
type: Number,
required: true
},
inStock: {
type: Number,
required: true
},
barCode: {
type: String,
required: true,
index: true,
unique: true
}
}, {
timestamps: {
createdAt: 'created_at',
updatedAt: 'updated_at'
}
});
并像这样导出:
module.exports = v1_connection.model('Product', ProductSchema);
所以,在同一个文件夹但另一个文件中,我得到了这两个 Schema(第一个嵌入在第二个中):
/*
Product in Sale Schema
*/
let InSaleProductSchema = new Schema({
product: {
type: Schema.ObjectId,
ref: 'Product',
unique: true
},
qty: {
type: Number,
},
total: {
type: Number,
},
inSale: {
type: Boolean
}
}, {
timestamps: {
createdAt: 'created_at',
updatedAt: 'updated_at'
}
});
/*
Sale Schema
*/
let SaleSchema = new Schema({
user: {
type: Schema.ObjectId,
ref: 'User'
},
products: [InSaleProductSchema],
total: {
type: Number,
},
isComplete: {
type: Boolean,
default: false
}
}, {
timestamps: {
createdAt: 'created_at',
updatedAt: 'updated_at'
}
});
嗯,问题是在预“保存”挂钩中指定的,谁想要从产品保存的文档中减去所需的数量。这就是问题所在
// Create and execute the query to find the product by de product ID
let query_product = Product.findById(product_id);
总是,当我不想运行钩子时,向我抛出一条错误消息:
TypeError: Product.findById is not a function
所以。 . .怎么了?
**如果你问我如何导入产品型号:const Product = require('./product');**
【问题讨论】:
-
你是在你的 presave 钩子里做的吗?
标签: node.js rest api express mongoose