将项目添加到猫鼬参考对象数组中的问题

时间:2019-04-22 16:10:28

标签: arrays node.js mongoose mongoose-schema

在我的NodeJS和MongoDB应用中,我有2种猫鼬模式:

companySchema:

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添加到products中的companySchema数组中,以便于稍后再访问产品。 为此,我写道:

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

1 个答案:

答案 0 :(得分:0)

您正在设置静态方法,该方法是模型上的方法,而不是文档实例。

因此,this是指模型本身,而不是单个文档。

与文档不同,模型没有名为“ 产品”的数组(可迭代),因此无法将其扩展到新的数组中。

尝试使用方法代替静态

companySchema.methods.addProduct = function (productId) {
  ...
}

我希望这会有所帮助。