首页 > 解决方案 > 将对象字面量数组传递给 Mongoose 模式之间的区别

问题描述

我只是想知道当从服务器接收 json 时,这段代码怎么会返回一个 _id 键。

const productSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'Please enter product name'],
    trim: true,
    maxLength: [100, 'Product name cannot exceed 100 characters'],
  },
  price: {
    type: Number,
    required: [true, 'Please enter product price'],
    maxLength: [5, 'Product price cannot exceed 5 characters'],
    default: 0.0,
  },
  description: {
    type: String,
    required: [true, 'Please enter product description'],
  },
  ratings: {
    type: Number,
    default: 0,
  },
  images: [
    {
      public_id: {
        type: String,
        required: true,
      },
      url: {
        type: String,
        required: true,
      },
    },
  ],
"images": 
[
            {
                "_id": "6070a2351c2fe84ab8883e4c",
                "public_id": "products/dsvbpny402gelwugv2le",
                "url": "https://res.cloudinary.com/bookit/image/upload/v1608062030/products/dsvbpny402gelwugv2le.jpg"
            }
        ],

我注意到从服务器请求时存在 _id 字段。这是自动的吗?

标签: javascriptnode.jsexpressmongoose

解决方案


您应该知道默认情况下,Mongoose 会在您的模式中添加一个 _id 属性。

您可以在这里了解更多信息:https ://mongoosejs.com/docs/guide.html#_id


推荐阅读