【问题标题】:how to find data into an array mongodb , nodejs如何在数组中查找数据 mongodb , nodejs
【发布时间】:2022-01-22 00:55:41
【问题描述】:

我正在从数组中查找数据。那是一门课程,我想通过标题找到一篇文章,该标题存储在课程的文章中。我一步一步来... (1) 我想听名字就知道课程, (2) 之后,我想通过文章的标题找到一篇文章到课程的文章中 (3) 并将文章和课程渲染到网页上 这是代码

const course = req.params.course
const article_title = req.query.article

Course.findOne({name: course , article:article_title}).then(function(data){
    console.log(data)
    res.render('article',{data :data})
}).catch((err)=>{console.log(err)});

这里是数据库

_id:61c057cfd70f2fb178d4e996
name:"Soft "
 discription:"House"
article:Array
    0:Object
    title:"Where does it come from?"
    content:"<p>Title is very important for an article to explain content | article..."
   _id:61c05d4a3905f61f72a8e61b
    1 :Object
    2:Object

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    要搜索,您可以使用:

    Couse.findOne({name: course, 'article.title': article_title})
    

    因此您将获得包含所需文章的文档。

    使用投影和$elemMatch,您可以过滤文章数组本身,以便只有您想要的子文档存在:

    Couse.findOne({name: course, 'article.title': article_title}, {
       article: {
          $elemMatch: {
             title: article_title
          }
       }
    })
    

    您可以在 MongoPlayground 中尝试一下 https://mongoplayground.net/p/SVXNGE6tuW7

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-19
      • 2019-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-28
      • 2019-02-23
      相关资源
      最近更新 更多