当我用这种方法查询时
let articles = await Article.find()
res.send(articles)会得到
[
{"cover": "\\uploads\\upload_a3770506ec4a3f5708ded093cc3f9c73.PNG",
"_id": "60b71a37ccf6920aec6992ad",
"title": "测试文章","
author": "60b22f16cc21cb31fc8f88a6",
"publishDate": "2021-06-04T00:00:00.000Z",
"content": "<p>大风歌</p>","__v": 0}
]
然后注释掉res.send 换成:
res.render('admin/article.art' ,{articles:articles});
把数据{{$value.author}}渲染到模板中
{{each articles}}
<tr>
<td>{{@$value._id}}</td>
<td>{{$value.title}}</td>
<td>{{$value.publishDate}}</td>
<td>{{$value.author}}</td>
{{/each articles}}
能正常渲染.
当换成这种关联查询时
let articles = await Article.find().populate('author');
res.send(articles)会得到
[
{"cover": "\\uploads\\upload_a3770506ec4a3f5708ded093cc3f9c73.PNG",
"_id": "60b71a37ccf6920aec6992ad","title": "测试文章",
"author": {"state": 0,"_id": "60b22f16cc21cb31fc8f88a6","username": "lituiping","email": "2869161658@qq.com","password": "$2b$10$y8oCNXQeekb3taymn7/5deS0IuTpU9RXNl/l553dbyp89820qKJt.","role": "admin","__v": 0},
"publishDate": "2021-06-04T00:00:00.000Z",
"content": "<p>大风歌</p>","__v": 0}
]
然后注释掉res.send 换成:
res.render('admin/article.art' ,{articles:articles});
把数据{{$value.author.username}}渲染到模板中
{{each articles}}
<tr>
<td>{{@$value._id}}</td>
<td>{{$value.title}}</td>
<td>{{$value.publishDate}}</td>
<td>{{$value.author.username}}</td>
{{/each articles}}
就会报错不知道什么原因
报错:SyntaxError: Unexpected token R in JSON at position 0
1.在populate后面增加.lean();
2.通过JSON.stringify()将mogoose文档 对象转换为字符串,再通过JSON.parse()转换为普通对象;