我正在尝试设计数据库模型,但是我不知道如何将array
的{{1}}和strings
的{{1}}放入其中。我当前的模型是:
array
objects
数据结构为const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const schema = new Schema({
email: { type: String, unique: true, required: true },
hash: { type: String, required: true },
createdDate: { type: Date, default: Date.now },
settings: {
favorites: { /* ??? */ },
cart: { /* ??? */ },
states: {
favorites: { type: Boolean, default: true },
search: { type: Boolean, default: false },
category: { type: Schema.Types.Mixed, default: false }
}
}
});
schema.set("toJSON", { virtuals: true });
module.exports = mongoose.model("User", schema);
favorites
的示例数据结构为:
['234', '564', '213', '782']
如何将其作为配置添加到cart
模型中?
答案 0 :(得分:1)
收藏夹必须是这样的String数组:favorites: [String]
对于购物车数组,我们有两个主要选择:
subdocuments
的数组。const schema = new Schema({
email: { type: String, unique: true, required: true },
hash: { type: String, required: true },
createdDate: { type: Date, default: Date.now },
settings: {
favorites: [String],
cart: [
{
quantity: Number,
marketId: String
}
],
states: {
favorites: { type: Boolean, default: true },
search: { type: Boolean, default: false },
category: { type: Schema.Types.Mixed, default: false }
}
}
});
schema types
的数组。const schema = new Schema({
email: { type: String, unique: true, required: true },
hash: { type: String, required: true },
createdDate: { type: Date, default: Date.now },
settings: {
favorites: [String],
cart: [
new Schema({
quantity: Number,
marketId: String
})
],
states: {
favorites: { type: Boolean, default: true },
search: { type: Boolean, default: false },
category: { type: Schema.Types.Mixed, default: false }
}
}
});
对于这两个文件,当您创建文档时,它看起来都是这样,请注意,猫鼬在卡片项目中添加了_id字段。
{
"settings": {
"states": {
"favorites": true,
"search": false,
"category": false
},
"favorites": [
"234",
"564",
"213",
"782"
],
"cart": [
{
"_id": "5e6cd0bd53feb32d50699b79",
"quantity": 5,
"marketId": "234"
},
{
"_id": "5e6cd0bd53feb32d50699b78",
"quantity": 2,
"marketId": "564"
},
{
"_id": "5e6cd0bd53feb32d50699b77",
"quantity": 7,
"marketId": "213"
},
{
"_id": "5e6cd0bd53feb32d50699b76",
"quantity": 3,
"marketId": "782"
}
]
},
"_id": "5e6cd0bd53feb32d50699b75",
"email": "abc@def.net",
"hash": "hash...",
"createdDate": "2020-03-14T12:40:29.969Z",
"__v": 0,
"id": "5e6cd0bd53feb32d50699b75"
}
如果您不希望购物车数组中有_id
个字段,则可以添加_id: false
选项,如下所示:
cart: [
new Schema(
{
quantity: Number,
marketId: String
},
{ _id: false }
)
],
以下是一些有用的文档: