[英]Generate mongoose schema for dynamically populated array of objects
这是我的对象数组:
[
{
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({});
放什么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 BodySchema = new Schema({
data: [{
ready: Boolean,
body: String
}]
});
所以你要存储在数据库中的数据是两个简单的属性,你可以使用以下模式:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.