试图解析猫鼬对象
Trying to parse a mongoose object
所以我正在调用 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
。
我如何解析它以便我可以使用属性 author
和 assigment
.
如有任何帮助,我们将不胜感激。
试试下面的代码:
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 是异步的,它不会等到数据库操作 Coursework.find({})
完成。所以你需要等到 DB find 调用完成,然后 arr
将填充数据,而且为了打印我们不需要使用 .lean()
但如果你想 alter/manipulate returned 文档中的字段然后您必须将 mongoose 文档转换为 .Js 对象以供进一步使用。此外,您需要将此代码包装在 try-catch
块中,因为建议将 async
函数包装在 try catch.
中
注意: 如果您正在使用 author._id
检查 author
- 在唯一字段上进行过滤,然后尝试使用 .findOne()
这将 return null
或匹配的文档,这有助于我们避免对数组进行不必要的迭代。
这一行let arr = Coursework.find({ })
returns一个文件数组。您必须遍历 arr
才能获得特定的分配,而简单的 arr.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);
}
}
所以我正在调用 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
。
我如何解析它以便我可以使用属性 author
和 assigment
.
如有任何帮助,我们将不胜感激。
试试下面的代码:
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 是异步的,它不会等到数据库操作 Coursework.find({})
完成。所以你需要等到 DB find 调用完成,然后 arr
将填充数据,而且为了打印我们不需要使用 .lean()
但如果你想 alter/manipulate returned 文档中的字段然后您必须将 mongoose 文档转换为 .Js 对象以供进一步使用。此外,您需要将此代码包装在 try-catch
块中,因为建议将 async
函数包装在 try catch.
注意: 如果您正在使用 author._id
检查 author
- 在唯一字段上进行过滤,然后尝试使用 .findOne()
这将 return null
或匹配的文档,这有助于我们避免对数组进行不必要的迭代。
这一行let arr = Coursework.find({ })
returns一个文件数组。您必须遍历 arr
才能获得特定的分配,而简单的 arr.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);
}
}