arrays - 为动态填充的对象数组生成 Mongoose 模式

标签 arrays database mongodb mongoose mongoose-schema

这是我的对象数组:

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

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

最佳答案

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

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

关于arrays - 为动态填充的对象数组生成 Mongoose 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55920838/

相关文章:

c - 需要类型为 'int' 的参数,但参数 2 的类型为 'int **'

javascript - 如何从数组中的数据创建对象中的键?

database - 在数据库列中存储分隔列表真的那么糟糕吗?

node.js - mongoose.connect(connectionSring) 如何工作?

node.js - 获取 Kue 作业的结果并通过开放连接将其推送给客户端

arrays - 尼姆 : advantage of using array over seq?

c - 为了安全起见,我应该始终动态分配数组吗?

ruby-on-rails - 没有这样的文件或目录服务器是否在本地运行并接受 Unix 域套接字 "/tmp/.s.PGSQL.5432"上的连接?

database - 在设计用于数据挖掘的数据库模式时应该注意什么?

mongodb - mongoimport : 'error validating settings: only one positional argument is allowed'