【问题标题】:Generate mongoose schema for dynamically populated array of objects为动态填充的对象数组生成猫鼬模式
【发布时间】:2019-09-19 02:38:02
【问题描述】:

这是我的对象数组:

 [
        {
            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"
            },
        ]

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

【问题讨论】:

    标签: arrays database mongodb mongoose mongoose-schema


    【解决方案1】:

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

    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的文档

    【讨论】:

    • 谢谢,我也试过了……出于某种奇怪的原因,data = []; 发生了。我得到空数组。你想聊聊这个吗?
    • 您应该编辑您的问题并添加您检索数据的方式。您使用什么工具来知道您的数据库中有数据?
    • 我使用的是 Robo 3T,之前是 Robomongo。
    • 已编辑,请检查我的问题。
    • 工作!谢啦!!我完全忘记了insertMany()。现在说得通了..
    【解决方案2】:

    我会这样定义:

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

    【讨论】:

      猜你喜欢
      • 2014-11-25
      • 2019-11-27
      • 2021-08-16
      • 2020-06-28
      • 2020-11-24
      • 2019-10-30
      • 2014-04-19
      • 1970-01-01
      相关资源
      最近更新 更多