亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

嘗試解析貓鼬對象

嘗試解析貓鼬對象

米琪卡哇伊 2022-08-27 09:48:37
所以我調用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);以下是我稱之為科西嘉會的路線: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()})    }}我需要在視圖中使用賦值。每次我試圖字符串化時,它都會顯示為.如何解析它,以便使用屬性和.undefinedauthorassigment任何幫助將不勝感激。
查看完整描述

2 回答

?
交互式愛情

TA貢獻1712條經驗 獲得超3個贊

此行返回一個文檔數組。您必須迭代才能獲得特定的賦值,而簡單操作將不起作用let arr = Coursework.find({  })arrarr.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);

    }

}


查看完整回答
反對 回復 2022-08-27
?
梵蒂岡之花

TA貢獻1900條經驗 獲得超5個贊

試試下面的代碼:


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操作完成。因此,您需要等到DB find調用完成,然后將填充數據,并且對于打印,我們不需要使用,但是如果您想更改/操作返回文檔中的字段,那么您必須將貓鼬文檔轉換為。供進一步使用的 Js 對象。此外,您需要將此代碼包裝在塊中,因為建議將函數包裝在try catch中。Coursework.find({})arr.lean()try-catchasync


注意:如果您正在檢查對唯一字段的 using - 類型的篩選,請嘗試使用將返回其中一個或匹配的文檔,這有助于我們避免對數組進行不必要的迭代。authorauthor._id.findOne()null


查看完整回答
反對 回復 2022-08-27
  • 2 回答
  • 0 關注
  • 121 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號