【发布时间】:2019-09-11 19:45:33
【问题描述】:
在我的 NodeJS 和 MongoDB 应用程序中,我有 2 个猫鼬模式:
公司架构:
const companySchema = new Schema({
name: {
type: String,
required: true
},
products: [{
type: Schema.Types.ObjectId,
ref: 'Product',
required: false
}]
});
companySchema.statics.addProduct = function (productId) {
let updatedProducts = [...this.products];
updatedProducts.push(productId);
this.products = updatedProducts;
return this.save();
}
module.exports = mongoose.model(‘Company’, companySchema);
productSchema:
const productSchema = new Schema({
name: {
type: String,
required: true
},
quantity: {
type: Number,
required: true
}
});
module.exports = mongoose.model('Product', productSchema);
每次我向productSchema添加新产品时,我想将新创建的产品的_id添加到companySchema中的products数组中,以便以后轻松访问产品。
为此,我写道:
const Company = require('../models/company');
const Product = require('../models/product ');
exports.postAddProduct = (req, res, next) => {
const name = req.body.name;
const quantity = req.body.quantity;
const product = new Product({
name: name,
quantity: quantity
});
product.save()
.then(product => {
return Company.addProduct(product._id);
})
.then(result => {
res.redirect('/');
})
.catch(err => console.log(err));
}
我收到一个错误:TypeError: this.products is not iterable。
【问题讨论】:
标签: arrays node.js mongoose mongoose-schema