因此,我正在调用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
。
任何帮助将不胜感激。
答案 0 :(得分:1)
此行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);
}
}
答案 1 :(得分:0)
尝试以下代码:
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)
/**
* As `.find()` returns an array & to access `assignment` field on each doc, You need to iterate over.
* let val = JSON.stringify(arr.assignment) has to be replaced
*/
let val = arr.map((i)=> {return JSON.stringify(i.assignment)}) // will be an array of parsed `assignment` values
//console.log(val)
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
中将填充数据,并且仅出于打印目的,我们不需要使用.lean()
,但是如果您要更改/操作其中的字段,返回的文档,则必须将猫鼬文档转换为.Js对象以供进一步使用。另外,您需要将此代码包装在try-catch
块中,因为建议将async
函数包装在try catch中。
注意::如果您正在使用author
检查author._id
-对唯一字段进行过滤,请尝试使用.findOne()
,它将返回null
或匹配的文档,可以帮助我们避免在数组上进行不必要的迭代。