试图解析猫鼬对象

问题描述 投票:0回答:2

因此,我正在调用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。如何解析它,以便可以使用属性authorassigment

任何帮助将不胜感激。

javascript node.js mongodb ejs
2个回答
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)
            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中。


0
投票

此行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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.