首页 > 解决方案 > 为动态填充的对象数组生成猫鼬模式

问题描述

这是我的对象数组:

 [
        {
            ready: true,
            body: "Body 1"
        },
        {
            ready: true,
            body: "Body 3"
        },
        {
            ready: true,
            body: "Body 3"
        },
    ]

现在,如果我想生成一个模式,我通常会这样做:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const BodySchema = new Schema({

});

mongoose.model('Body', BodySchema);

我需要知道在new Schema({});声明中放什么,这样它才能接受对象数组。

谢谢。

编辑:

这就是我格式化数据的方式:

try {
        const retrievedFull = await getFullData();
        const data = await retrievedFull.map(({ready, body}) => ({
            ready,
            body
        }))

       const finalData = new Body(data) //instantiate Schema
       return res.status(200).json({
            success: true,
            data: finalData
        })

    } catch(err) {
        console.log(err);
    }

来自getFullData()

[
            {
                ready: true,
                body: "Body 1",
                other_stuff: "Stuff 1"
            },
            {
                ready: true,
                body: "Body 2",
                other_stuff: "Stuff 2"
            },
            {
                ready: true,
                body: "Body 3",
                other_stuff: "Stuff 3"
            },
        ]

所以,基本上我剥离了所有我想要的属性并创建了一个新的对象数组。

标签: arraysdatabasemongodbmongoosemongoose-schema

解决方案


因此,您要存储在数据库中的数据是两个简单的属性,您可以使用以下模式:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const BodySchema = new Schema({
    ready: Boolean,
    body: String,
});

const BodyModel = mongoose.model('Body', BodySchema);

关于在数据库中存储数据的方式:

try {
  // Get the data from an external source
  const externalData = await getFullData();

  // Format the data
  const formattedData = externalData.map(({
    ready,
    body,
  }) => ({
    ready,
    body,
  }));

  // Insert the data in the database
  const databaseData = await BodyModel.insertMany(formattedData);

  // Returns the inserted data
  return res.status(200).json({
    success: true,
    data: databaseData,
  });
} catch (err) {
  console.log(err);
}

insertMany的文档


推荐阅读