【问题标题】:Is it possible to have two types of objects in an array of mongoose schema猫鼬模式数组中是否可以有两种类型的对象
【发布时间】:2020-12-04 18:43:12
【问题描述】:

我正在构建一个电子商务应用程序,这是我的订单模式。

const mongoose = require("mongoose");

const orderSchema = new mongoose.Schema({
    buyer: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "buyer",
        required: true
    },
    items: [{
        item: {
            type: mongoose.Schema.Types.ObjectId, 
            ref: "item",
    },
    quantity: {
        type: Number,
        default: 1
    }}
    ],
    seller: {
        type: mongoose.Schema.Types.ObjectId, 
        ref: "seller",
        required: true
    },
    location: {
        type: {
            type: "String",
            enum:['Point']
        },
        coordinates: {
            type: [Number],
            index: '2dsphere'
        }
    },
    sendAt:{
        type: Date,
        default: Date.now
    } 
});

const orderModel = mongoose.model("orders", orderSchema);
module.exports = orderModel;

我想要一个包含 item-reference-id 和数量的数组。 但是当我输入数据时,使用上述模式,每个项目都充当另一个子文档并具有_id。 Query response image.

【问题讨论】:

  • 我遇到了和你类似的问题,你解决了吗?
  • order: [ { _id: false, item: { type: mongoose.Schema.Types.ObjectId, ref: "items", required: true, }, 数量: { type: Number }, } , ],

标签: mongodb mongoose schema


【解决方案1】:

我找到了解决办法:

    order: [
    {
      _id: false,
      item: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "items",
        required: true,
      },
      quantity: { type: Number },
    },
  ],

_id: false 将阻止子文档为子文档创建另一个 ID。

【讨论】:

    猜你喜欢
    • 2021-05-04
    • 2019-10-30
    • 2019-08-21
    • 2017-06-20
    • 2019-06-09
    • 2021-01-24
    • 2019-08-30
    • 2013-07-15
    • 2016-11-09
    相关资源
    最近更新 更多