【问题标题】:Problem with adding an item to an array of mongoose reference objects将项目添加到猫鼬引用对象数组时出现问题
【发布时间】: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


    【解决方案1】:

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

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

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

    尝试使用 methods 而不是 statics

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

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2017-12-21
      • 2010-10-17
      • 2013-03-31
      • 1970-01-01
      • 2021-09-08
      • 2017-12-22
      • 2019-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多