Javascript Mongoose:如何在子文档数组中添加附加字段

Javascript Mongoose:如何在子文档数组中添加附加字段,javascript,mongodb,mongoose,subdocument,Javascript,Mongodb,Mongoose,Subdocument,我有一个关于mongoDB的问题,即mongoose: 假设我有两种模型: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 = mongo

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

假设我有两种模型: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);
当用户购买一些商品时,我只是将产品添加到用户模型中的purchases数组中(使用push方法)。如果我需要将购买的ID与其完整描述进行匹配,我将使用“填充”

问题是我需要以某种方式控制用户每次购买的数量->我需要数组中每个购买对象中的附加字段…类似于数量或总数,如下所示:

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

我被困住了,不知道如何实现这一点。上面的例子不起作用。

试试这个,这种方法肯定有效:

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

quantity
字段作为Userschema中的根字段,并使用
$inc
在每次购买时增加其数量。问题是,我需要控制每个购买的数量,也就是说,如果用户购买了一些商品,但它尚未出现在purches数组中,则应将其添加为带有quantity字段的对象。如果用户多次购买同一商品,数量计数器应增加错误是什么?没有错误,但也没有添加字段。在将其推入阵列后,我只看到purches的Id。即使我填充数据没有字段…一切都是无用的,你可能会使用radheyshyam,但在将来,当你使用这种类型的嵌套数据进行填充或聚合时,它会给你带来麻烦。Populatte
ref
键或更改键并填充该键以获取产品文档信息。谢谢radhey希亚姆。这绝对行得通!现在我需要找到一种方法来填充ref;)我很高兴您只需要在populate中传递key ref,比如:
user.findOne(条件)。populate({path:})。然后(result=>{console.log(result)})。catch(error=>{console.log(error);})