mongoose 如何在mongoDb中创建数组中的子对象时避免生成对象id

hts6caw3  于 2022-11-13  发布在  Go
关注(0)|答案(2)|浏览(180)

在我的文档中,我有一个images的数组,其中每个图像都有urlpublic_id。我只想要urlpublic_id,但也存储了_id的附加参数。我想避免这种情况。
在数据库中存储为:

"images": [
      {
        "url": "https://res.cloudinary.com/dpurb6xes/image/upload/v1665806337/vivans/po0zh7eots60azad3y5b.png",
        "public_id": "vivans/po0zh7eots60azad3y5b",
        "_id": "634a4db7177280021c56737c"
      },
      {
        "url": "https://res.cloudinary.com/dpurb6xes/image/upload/v1665806337/vivans/po0zh7eots60azad3y5b.png",
        "public_id": "vivans/po0zh7eots60azadasdb",
        "_id": "634a4db7177280021c56737d"
      }
    ],

Mongoose模式

const imageArray = new mongoose.Schema({
url: { type: String },
public_id: { type: String },
});

const productSchema = new mongoose.Schema({
    images: [imageArray],
});

我的帖子请求

{
"images": [
    {
      "url": "https://res.cloudinary.com/dpurb6xes/image/upload/v1665806337/vivans/po0zh7eots60azad3y5b.png",
      "public_id": "vivans/po0zh7eots60azad3y5b"
    },
    {
      "url": "https://res.cloudinary.com/dpurb6xes/image/upload/v1665806337/vivans/po0zh7eots60azad3y5b.png",
      "public_id": "vivans/po0zh7eots60azadasdb"
    }
  ],
}

如何去掉存储在数据库中的_id。

xmakbtuz

xmakbtuz1#

正在转换

const imageArray = new mongoose.Schema(
    {
        url: { type: String },
        public_id: { type: String },
    },
);

const imageArray = new mongoose.Schema(
    {
        url: { type: String },
        public_id: { type: String },
    },
    { _id: false }
);

解决了问题。

rsaldnfx

rsaldnfx2#

Schema类可以接收第二个参数,该参数用于传递一些选项,其中一个选项是“_id”,这是一个布尔值,因此您只需将_id属性设置为false来提供第二个参数,以避免在文档中创建_id属性。
这一来:

const imageArray = new mongoose.Schema({
    url: { type: String },
    public_id: { type: String },
}, { _id: false }
);

您可以在官方文档中查看整个选项列表:Mongoose方案-选项

相关问题