【问题标题】:Trying to parse a mongoose object试图解析一个猫鼬对象
【发布时间】:2020-05-22 03:54:55
【问题描述】:

所以我正在调用 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


    【解决方案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);
    }
    

    正如您在以下代码中看到的,sn-p 我创建了两个 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);
        }
    }
    

    【讨论】:

      【解决方案2】:

      试试下面的代码:

      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 是异步的,它不会等到 DB 操作 Coursework.find({}) 完成。因此,您需要等到 DB find 调用完成,然后arr 将填充数据并且仅用于打印我们不需要使用.lean(),但是如果您想更改/操作返回文档中的字段,那么您'必须将 mongoose 文档转换为 .Js 对象以供进一步使用。此外,您需要将此代码包装在 try-catch 块中,因为建议将 async 函数包装在 try catch 中。

      注意:如果您使用 author._id 检查 author - 对唯一字段进行过滤,请尝试使用 .findOne(),这将返回 null 或匹配的文档,这有助于我们避免对数组进行不必要的迭代。

      【讨论】:

      • 它仍然未定义
      • @RockySingh :哦,我的错,我忽略了&只检查了console.log(arr),但没有查看let val = JSON.stringify(arr.assignment),更新了我对所有场景的答案..
      猜你喜欢
      • 2019-01-15
      • 1970-01-01
      • 2017-04-27
      • 2013-01-13
      • 2015-09-15
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      • 2017-01-24
      相关资源
      最近更新 更多