我想实现的是这种功能,这是一篇博客的文章详情页里面的前一条数据id和标题和后一条数据id和标题
// 查询文章详情
async getArticle(ctx) {
const { id } = ctx.params;
const article = await Article.findOne({ _id: id }).populate([
{ path: "category" },
{ path: "tags" },
{ path: "author" }
]);
article.views++;
article.save();
const prev_article = await Article.findOne({ _id: { "$lt": id } }).sort({ _id: -1 }).limit(1);
const next_article = await Article.findOne({ _id: { "$gt": id } }).sort({ _id: 1 }).limit(1);
article.prev = prev_article ? { _id: prev_article._id, title: prev_article.title } : { message: "已是第一条文章" };
article.next = next_article ? { _id: next_article._id, title: next_article.title } : { message: "已是最后一条文章" };
ctx.body = article
? new Response().json(article)
: new Response().error("文章不存在~");
}
刚开始我是这样写的,后来查到好像mongoose查询后的数据不能增加属性,我不想重新再定义一个变量来增加,请问可以使用别的方法来实现吗? 我目前想到的是使用mongoose的虚拟属性是实现,但我发现好像碰到问题了
###应该是可以增加的,你查询出来的是 mongoose 文档格式,需要转换为 json 格式,在查询语句后面加一条 .lean()
const article = await Article.findOne({ _id: id }).populate([
{ path: "category" },
{ path: "tags" },
{ path: "author" }
]).lean();