arrays - 为动态填充的对象数组生成猫鼬模式
问题描述
这是我的对象数组:
[
{
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的文档
推荐阅读
- sql - 有没有办法在 SQL (BigQuery) 上加入两个查询
- r - ggplot2 - 将平均值添加到我的置信区间
- excel - 使用 Excel 和 PowerQuery 设计大规模考勤系统
- javascript - 为什么 Firefox 控制台只引用一些对象键?
- android - 无法在 Google Play 控制台中停用已关闭 (Alpha) 的曲目
- elasticsearch - 将默认值设置为 elasticsearch index.max_inner_result_window 参数
- mongodb - 如何使用 2 个 MongoDB 数据库运行项目?
- authentication - CakePHP 4.X 是否有用于 Active Directory 身份验证的扩展?
- php - (Laravel) Blade 模板引擎和 AMP Mustache 之间的冲突
- flutter - 当应用程序在颤振中处于恢复状态时尝试更新变量的值