我正在作为个人技能开发项目开发一款用于朋友游戏的角色表应用程序,其mongoDB数据库存储数据并由React为前端提供动力。
我有两个Schema / model,其中一个是另一个的子文档。
主要型号:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CharacterSchema = new mongoose.Schema({
name: String,
caste: {
type: Schema.Types.ObjectId,
ref: 'Caste'
},
supernal: String,
anima: String,
description: String,
concept: String,
attributes: [
{
name: String,
dots: Number,
attributeType: String
},]
},
);
const Character = mongoose.model('Character', CharacterSchema);
module.exports = Character;
子文档模型/架构:
const mongoose = require('mongoose');
const CasteSchema = new mongoose.Schema({
name: String,
description: String,
});
const Caste = mongoose.model('Caste', CasteSchema);
module.exports = Caste;
我运行了一个种子文件,以一些入门数据填充数据库,当我访问所有已渲染的网址时,一切都显示正常,但“ Caste”字段除外,该字段仅会渲染对象的“ _id”值。这是正确的,因此一些数据已经通过发送,但是就像“名称”和“描述”键被遗忘了一样。我用Compass进行了检查,种子文件中的所有数据都被传递到了数据库中,只是没有传递到React前端。
从种子文件填充数据库的功能:
const seedCharacters = async () => {
try {
let userId = await seedUsers();
character_list.forEach(character => character.user = userId);
await db.Caste.deleteMany({}, (err, castes) => {
console.log(`Deleted all castes`);
db.Caste.create(caste_list, (err, castes) => {
if (err) {
console.log(err);
return;
}
console.log(`Created ${castes.length} castes.`);
db.Character.deleteMany({}, (err, characters) => {
console.log(`Deleted all characters`);
character_list.forEach((characterData) => { //Must be the last step
const character = new db.Character({
name: characterData.name,
caste: characterData.caste,
supernal: characterData.supernal,
anima: characterData.anima,
concept: characterData.concept,
description: characterData.description,
attributes: characterData.attributes, //TODO - add the rest
});
db.Caste.findOne({name: characterData.caste}, (err, foundCaste) => {
console.log(`Found character ${character.name} with the caste ${foundCaste.name}`);
if (err) {
console.log(err);
return;
}
character.caste = foundCaste;
character.save((err, savedCharacter) => {
if (err) {
console.log(err);
return;
}
console.log(`Saved ${savedCharacter.name} of ${foundCaste.name}`);
process.exit();
});
});
});
});
});
});
} catch (err) {
console.log(`Seed Characters error: ${err}`);
process.exit(1);
}
}
组件从容器文件中装入/渲染了步骤,该容器文件从种子文件中接收数据:
componentDidMount() {
CharacterApi.index()
.then(res => {
if (res.status === 200) {
this.setState({
characters: res.data
})
}
})
.catch(err => console.log(`componentDidMount error: ${err}`));
}
render() {
let characters = this.state.characters;
return(
<div className="characterContainer">
{characters && characters.map(character => {
return <Character character={character} key={character._id} handleEdit={this.handleEdit} handleDelete={this.handleDelete} />
})}
{!characters &&
<>
<p>No characters to show</p>
</>
}
</div>
)
}
那么我如何从传递给网页的子文档中获取“名称”和“描述”值,而不是“ _id”?