因此,我正在调用mongodb,但在解析数据时遇到了麻烦,因此无法将其传递给视图。我用EJS编写了前端。
这是我要呼叫的模型:
const CourseworkSchema = new Schema({
assignment: [
{
type: String
}
],
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
name: String
}
})
module.exports = mongoose.model('Coursework', CourseworkSchema);
这是我称呼Corsework的路线:
app.get('/dashboard', (req, res) => {
if(req.isAuthenticated()){
if(req.user.isTeacher) {
// render dashboard for teacher
//let author = author._id
let arr = Coursework.find({ })
//console.log(arr)
let val = JSON.stringify(arr.assignment)
//console.log(val)
console.log(arr.assignment)
res.render('instructor', {arr: val, isAuth:req.isAuthenticated()})
}else {
// render dashboard for student
res.render('student', {isAuth: req.isAuthenticated()})
}
}
我需要在视图中使用分配。每次我尝试进行字符串化时,都会显示为undefined
。如何解析它,以便可以使用属性author
和assigment
。
任何帮助将不胜感激。
尝试以下代码:
app.get('/dashboard', async (req, res) => {
if(req.isAuthenticated()){
if(req.user.isTeacher) {
// render dashboard for teacher
//let author = author._id
let arr = await Coursework.find({ }).lean(true).exec();
//console.log(arr)
let val = JSON.stringify(arr.assignment)
//console.log(val)
console.log(arr.assignment)
res.render('instructor', {arr: val, isAuth:req.isAuthenticated()})
}else {
// render dashboard for student
res.render('student', {isAuth: req.isAuthenticated()})
}
}
由于Node.Js是异步的,它不会等到数据库操作Coursework.find({ })
完成。因此,您需要等待直到DB find调用完成,然后arr
将填充数据,并且还需要将猫鼬文档转换为.Js对象以供进一步使用,您需要使用.lean(true)
。除了此代码外,您还需要将此代码包装在try-catch
块中,因为建议将async
函数包装在try catch中。
此行let arr = Coursework.find({ })
返回文档数组。您必须遍历arr
才能获得特定的分配,而简单的arr.assignment
将不起作用
例如
let arr = await Coursework.find({ })
for (const doc of arr) {
console.log(doc.assignment);
console.log(doc.author);
}
您可以在下面的代码片段中看到,我创建了两个CourseWork项目,然后对其进行迭代以将其记录到控制台中>]
const mongoose = require('mongoose');
run().catch(error => console.log(error.stack));
async function run() {
await mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
await mongoose.connection.dropDatabase();
const CourseworkSchema = new mongoose.Schema({
assignment: [
{
type: String
}
],
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
name: String
}
});
const CourseWork = mongoose.model('Coursework', CourseworkSchema);
await CourseWork.create({ assignment: "first assignment", author: { name: "first author" }});
await CourseWork.create({ assignment: "Second assignment", author: { name: "second author" }});
const docs = await CourseWork.find();
console.log(docs);
for (const doc of docs) {
console.log(doc.assignment);
console.log(doc.author);
}
}