2 回答

TA貢獻(xiàn)1712條經(jīng)驗(yàn) 獲得超3個(gè)贊
此行返回一個(gè)文檔數(shù)組。您必須迭代才能獲得特定的賦值,而簡(jiǎn)單操作將不起作用let arr = Coursework.find({ })arrarr.assignment
例如
let arr = await Coursework.find({ })
for (const doc of arr) {
console.log(doc.assignment);
console.log(doc.author);
}
正如您在以下代碼片段中看到的那樣,我創(chuàng)建了兩個(gè)CourseWork項(xiàng)目,然后迭代它們以將它們記錄到控制臺(tái)
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);
}
}

TA貢獻(xiàn)1900條經(jīng)驗(yàn) 獲得超5個(gè)贊
試試下面的代碼:
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是異步的,它不會(huì)等到DB操作完成。因此,您需要等到DB find調(diào)用完成,然后將填充數(shù)據(jù),并且對(duì)于打印,我們不需要使用,但是如果您想更改/操作返回文檔中的字段,那么您必須將貓鼬文檔轉(zhuǎn)換為。供進(jìn)一步使用的 Js 對(duì)象。此外,您需要將此代碼包裝在塊中,因?yàn)榻ㄗh將函數(shù)包裝在try catch中。Coursework.find({})arr.lean()try-catchasync
注意:如果您正在檢查對(duì)唯一字段的 using - 類型的篩選,請(qǐng)嘗試使用將返回其中一個(gè)或匹配的文檔,這有助于我們避免對(duì)數(shù)組進(jìn)行不必要的迭代。authorauthor._id.findOne()null
添加回答
舉報(bào)