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);
}
}

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
添加回答
舉報