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
添加回答
举报