【问题标题】:Mongo DB.find returning empty array [duplicate]Mongodb.find返回空数组[重复]
【发布时间】:2021-06-22 19:47:11
【问题描述】:

我有这行代码

    const comments = await db.Comment.find({post: req.params.post_id});
    return res.status(200).json({comments});

请求已成功发送到后端,但 cmets 响应为空数组

/*
  res code: 200
*/

{
 comments: []
}

我检查了其他数据库功能,它们都可以正常工作,例如添加评论、编辑等

我的评论集是这样的

{"_id":{"$oid":"605d1faeb202e4425c004be9"},"text":"Welcome to this comment","user":{"$oid":"5ff5d878dd830142686b7fd5"},"post":{"$oid":"6016f770ea76030d24688f89"},"createdAt":{"$date":{"$numberLong":"1616715694247"}},"updatedAt":{"$date":{"$numberLong":"1616715694247"}},"__v":{"$numberInt":"0"}}


--------------------------------------------------------
{"_id":{"$oid":"605d1fb8b202e4425c004bea"},"text":"Welcome to this comment2","user":{"$oid":"5ff5d878dd830142686b7fd5"},"post":{"$oid":"6016f770ea76030d24688f89"},"createdAt":{"$date":{"$numberLong":"1616715704381"}},"updatedAt":{"$date":{"$numberLong":"1616715704381"}},"__v":{"$numberInt":"0"}}

我正在尝试按在我的评论收藏中保存为帖子的帖子 ID 进行搜索

【问题讨论】:

标签: javascript node.js mongodb mongoose mongodb-query


【解决方案1】:

我认为您需要将 req.params.post_id 包装在 ObjectId 中。

像这样

const ObjectId = require('mongoose').Types.ObjectId;

const comments = await db.Comment.find({
   post: new ObjectId(req.params.post_id)
});

【讨论】:

  • Mongoose: comments.find({ 'post.$oid': '6059444e21d546156cfce227' }, { projection: {} }) 还是不行
  • 您是否遇到任何错误?
  • 还是空数组?
  • 返回了空数组
  • 我认为您需要将 req.params.post_id 包装在 ObjectId 中。试试我更新的答案
猜你喜欢
  • 1970-01-01
  • 2017-11-01
  • 2014-05-01
  • 2016-06-29
  • 1970-01-01
  • 2018-09-05
  • 1970-01-01
  • 2021-12-25
  • 1970-01-01
相关资源
最近更新 更多