【发布时间】:2020-08-03 15:19:51
【问题描述】:
我想映射一个 mongoose Schema 上的数组: (数据注释)
const {Schema, model} = require("mongoose");
const noteSchema= new Schema({
idNote: {type: String, required: true, unique: true},
dataNotes: [{
title: {type:String, isRequired: true},
authors: [{type: String, fecha: Date}] }]
}, {timestamps:true});
module.exports = model("noteSchema", noteSchema);
我从后端响应数据:
noteCtrl.getNoteInfo = async (req, res) => {
await noteSchema.findOne({idNota: req.body.id})
.then((response)=>{
console.log(response)
res.send(response);
})
console.log(req.body)
}
这里的数据被很好地发送,作为一个对象
我的前端有:
ObtNofNotes = async () => {
await axios.post("http://localhost:4000/api/users/notes", {
id:
JSON.parse(localStorage.getItem("user")).user
})
.then((res) => {
console.log("Notes data " + res.data.dataNotes)
//It only returns [object Object] for each array
return this.notesArray(res.data.dataNotes)
})
.catch((err) => console.log(err));
}
notesArray= (n) => {
n.map(nm => {
console.log(nm)
//it returns the arrays just fine
return (<li>{nm.dataNotes[0][0]}</li>)
})
}
但是当我想渲染 li 时:
render() {
return (
<div>
{this.ObtNofNotes()}
</div>
)
}
React 返回错误:“对象作为 React 子级无效(找到:[object Promise])。如果您要渲染子级集合,请改用数组。”
但是数据已经在一个数组中,当我在 n.map() 函数中使用 console.log(nm) 时,它会返回每个数组和其中的对象。
我做错了什么?
我认为它与异步函数和承诺有关,因为它渲染 this.ObtNofNotes(),一个异步函数,我不确定它是否在渲染之前有数据,或者它是否在之前等待数据渲染,但我不确定。我是 React 新手,非常感谢您的帮助!
【问题讨论】:
标签: javascript node.js reactjs mongodb mongoose