简体   繁体   中英

Generate mongoose schema for dynamically populated array of objects

This is my array of objects:

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

Now if I want to generate a schema I'd normally do something like this:

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

const BodySchema = new Schema({

});

mongoose.model('Body', BodySchema);

I need to know what to put inside the new Schema({}); declaration so it would accept the array of objects.

Thanks.

EDIT:

This is how I format data:

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);
    }

The response from 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"
            },
        ]

So, basically I strip all the properties I want and make a new array of objects.

I would define it this way:

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

So the data you want to store in database are two simple attributes, you can use the following schema :

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

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

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

About the way to store the data inside of the database :

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);
}

Documentation of insertMany

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM