Javascript 正在尝试分析mongoose对象
因此,我正在调用mongodb,在解析数据以便将其传递给视图时遇到了问题。我用EJS编写前端 这就是我要呼叫的模型:Javascript 正在尝试分析mongoose对象,javascript,node.js,mongodb,ejs,Javascript,Node.js,Mongodb,Ejs,因此,我正在调用mongodb,在解析数据以便将其传递给视图时遇到了问题。我用EJS编写前端 这就是我要呼叫的模型: const CourseworkSchema = new Schema({ assignment: [ { type: String } ], author: { id: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, name:
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()})
}
}
我需要在视图中使用赋值。
每次我试图将其字符串化时,它都被认为是未定义的。
如何解析它,以便使用属性author和assignment
任何帮助都将不胜感激 请尝试以下代码:
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操作Coursework.find{}完成。因此,您需要等待DB find调用完成,然后arr将被填充数据,并且仅用于打印,我们不需要使用.lean,但如果您想更改/操作返回文档中的字段,则必须将mongoose文档转换为.Js对象以供进一步使用。此外,您需要在try-catch块中包装此代码,因为建议在try-catch中包装异步函数
注意:如果您正在使用author.\u id-对唯一字段进行筛选,那么请尝试使用.findOne,它将返回null或匹配的文档,这有助于我们避免在数组上进行不必要的迭代。此行让arr=Coursework.find{}返回一个文档数组。您必须迭代arr以获得特定的赋值,而简单的arr.assignment将不起作用
e、 g
正如您在下面的代码片段中所看到的,我创建了两个课程项目,然后对它们进行迭代以将它们记录到控制台
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);
}
}
还是undefined@RockySingh:哦,糟糕,我忽略了&只检查了console.logarr,但没有检查let val=JSON.stringifyarr.assignment,更新了所有场景的答案。。
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);
}
}