【问题标题】:Mongoose: How to add additional field into subdocument arrayMongoose:如何将附加字段添加到子文档数组中
【发布时间】:2019-01-04 21:27:18
【问题描述】:

我有一个关于mongoDB的问题,即mongoose:

假设我有 2 个模型:1)产品模型 2)用户模型

const ProductSchema = new Schema({
  title: String,
  description: String,
  product_type: String,
  image_tag: String,
  created_at: Number,
  price: Number
});
const Product = module.exports = mongoose.model('product', ProductSchema);

const UserSchema = new Schema({
  login: String,
  email: String,
  password: String,
  purchases: [{
    type: Schema.Types.ObjectId,
    ref: 'product'
  }]
});
const User = module.exports = mongoose.model('user', UserSchema);

当用户购买一些商品时,我只是将产品添加到用户模型中的购​​买数组中(使用推送方法)。如果我需要将购买的 ID 与其完整描述相匹配,我使用填充。

问题是我需要以某种方式控制用户每次购买的数量 -> 我需要在数组内的每个购买对象中添加额外的字段...类似数量或总计,就像这样:

const UserSchema = new Schema({
     ...
      purchases: [{
        type: Schema.Types.ObjectId,
        ref: 'product',
        quantity: {
          type: Number,
          default: 1
        }
      }]
    });

我被卡住了,不知道如何实现它。上面的例子不起作用。

【问题讨论】:

  • quantity字段作为Userschema中的根字段,并在每次购买时使用$inc增加其数量
  • 问题是我需要控制每次购买的数量,也就是说,如果用户购买了一些商品并且它还没有出现在 purches 数组中,则应该将其添加为带有数量字段的对象.如果用户多次购买相同的商品数量计数器应该增加
  • 错误是什么?
  • 没有错误,但也没有添加字段。将其推入数组后,我只看到购买的 ID。即使我填充数据没有字段......一切都没有用哭
  • 您可能会选择 radheyshyam,但将来当您使用该类型的嵌套数据进行一些填充或聚合时,它会给您带来麻烦

标签: javascript mongodb mongoose subdocument


【解决方案1】:

试试这个,这个方法肯定行:

const UserSchema = new Schema({
    purchases: [{
            ref: {
                 type: Schema.Types.ObjectId,
                 ref: 'product'
            },
            quantity: {
              type: Number,
              default: 1
            }
          }]
 });

【讨论】:

  • Populagte ref 密钥或更改密钥并填充该密钥以获取产品文档信息。
  • 谢谢你 radhey shyam。它肯定会奏效!现在我需要找到一种方法来填充 ref ;)
  • 我很高兴您只需要在填充中传递密钥引用,例如:user.findOne(Criteria).populate({ path: "<key>" }).then(result => { console.log(result) }).catch(error => { console.log(error); })
猜你喜欢
  • 1970-01-01
  • 2020-02-23
  • 2014-07-29
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 2017-08-31
相关资源
最近更新 更多