javascript - Mongoose:如何将附加字段添加到子文档数组中
问题描述
我有一个关于 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
}
}]
});
我被卡住了,不知道如何实现这一点。上面的例子不起作用。
解决方案
试试这个,这种方法肯定行得通:
const UserSchema = new Schema({
purchases: [{
ref: {
type: Schema.Types.ObjectId,
ref: 'product'
},
quantity: {
type: Number,
default: 1
}
}]
});
推荐阅读
- r - 如何在 ggplot2 平面图中增加轴线宽度?
- asp.net - ASP.NET 返回 HTTP 500 而不是 404
- ruby-on-rails - Rails:为什么has_many关系没有保存在像belongs_to这样的变量/属性中?
- ruby-on-rails - rails searchkick 错误:未找到字段 [word_middle] 的分析器 [searchkick_word_middle_index]
- react-native - “在此服务器上找不到请求 URL /index.bundle”是什么意思?
- sql-server - 创建具有通用数据类型的列?
- python - 如何在不使用 Tensofrlow 张量的情况下制作 Keras 自定义层?
- django - django-rules:将规则/谓词放在哪里?
- react-native - React-Navigation:使用 react-native-screens 的性能优化是否也可用于 TabNavigation?
- flutter - Dart:读取字段的注释值