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

Problem with adding an item to an array of mongoose reference objects

在我的 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);

产品架构:

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

您正在设置一个 static 方法,这是模型上的方法而不是文档实例上的方法。

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

与文档不同,该模型没有名为 products 的数组(可迭代),因此无法将其展开到新数组中。

尝试使用 方法 而不是 statics:

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

希望对您有所帮助。