简体   繁体   English

猫鼬:如何将其他字段添加到子文档数组

[英]Mongoose: How to add additional field into subdocument array

I have a question regarding mongoDB, namely mongoose: 我对mongoDB有一个疑问,即mongoose:

Let's say I have 2 models: 1) Product model 2) User model 假设我有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);

When the user buys some goods, I just add product to purchases array in user model(using push method). 当用户购买商品时,我只是将产品添加到用户模型的购买数组中(使用推方法)。 If I need to match purchase's ID to its full description I use populate. 如果需要将购买的ID与完整的描述相匹配,请使用填充。

The problem is I need somehow to control quantity of each purchase made by user -> I need additional field in each purchase object inside array...something like quantity or total, like that: 问题是我需要以某种方式控制用户进行的每次购买的数量->我需要在数组内的每个购买对象中添加其他字段...诸如数量或总计之类的东西:

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

I'm stuck and have no clue how to implement this. 我被困住了,不知道如何实现这一点。 Example above does not work. 上面的示例不起作用。

Try this, this way will definitely work: 试试这个,这种方式肯定会起作用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM