通过 Mongoose、Node.js、MongodDB 中的特定属性查找嵌入文档

发布于 2024-11-03 10:01:22 字数 994 浏览 2 评论 0原文

对于这个应用程序,我使用 Node.js、MongoDB、Mongoose 和Express

所以我有一个包含枢轴数组的参数对象,我想从枢轴读取某些数据,如下所述

---in models.js-------------------------
    var Pivot = new Schema({
    value : String
  , destination : String
  , counter : Number
 });


var Param = new Schema({
    title : String
  , desc : String
  , pivots : [Pivot]
});


------------- in main.js --------------

var Param = db.model('Param');


app.get('/:title/:value', function(req, res){
    Param.findOne({"title":req.param('title')}, function(err, record){
           console.log(record.pivots);
           record.pivots.find({"value":req.param('value')}, function(err, m_pivot){
                    pivot.counter++;
                    res.redirect(m_pivot.destination);
           });
           record.save();
    });
});

我知道代码在 console.log(record.pivots) 之前一直有效,因为我得到了一个文档集合右枢轴文档在里面。

但是,似乎没有一种查找方法可以让我通过架构中定义的“值”属性来匹配嵌入文档。是否可以使用 .find() 或 .findOne() 搜索这个嵌入文档数组,如果不能,是否有一些简单的方法可以通过猫鼬访问它?

For this app, I'm using Node.js, MongoDB, Mongoose & Express

So I have a Param Object that contains an array of Pivots, and I want to read certain data from the pivots as outlined below

---in models.js-------------------------
    var Pivot = new Schema({
    value : String
  , destination : String
  , counter : Number
 });


var Param = new Schema({
    title : String
  , desc : String
  , pivots : [Pivot]
});


------------- in main.js --------------

var Param = db.model('Param');


app.get('/:title/:value', function(req, res){
    Param.findOne({"title":req.param('title')}, function(err, record){
           console.log(record.pivots);
           record.pivots.find({"value":req.param('value')}, function(err, m_pivot){
                    pivot.counter++;
                    res.redirect(m_pivot.destination);
           });
           record.save();
    });
});

I know that the code works until console.log(record.pivots), since i got a doc collection with the right pivot documents inside.

However, there does not seem to be a find method to let me match an embedded document by the 'value' property defined in the schema. Is it possible to search through this array of embedded documents using .find() or .findOne() , and if not, is there some easy way to access it through mongoose?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

迷荒 2024-11-10 10:01:23

我认为您正在寻找“$in”关键字?

如:

{a: {$in: [10, "hello"]}}

来源: MongoDB 查询 CheatSheet

I think you are looking for the "$in" keyword?

As in:

{a: {$in: [10, "hello"]}}

source: MongoDB Queries CheatSheet

兔姬 2024-11-10 10:01:22

varunsrin,

这应该可以做到这一点

app.get('/:title/:value', function(req, res) {
  Param.findOne({'pivots.value': req.param('value'), "title":req.param('title')}},
                function(err, record) {
                  record.pivot.counter++;
                  res.redirect(m_pivot.destination);  
                 record.save();
               });
});

注意查询的复数形式以匹配模式中的字段名称

varunsrin,

This should do it

app.get('/:title/:value', function(req, res) {
  Param.findOne({'pivots.value': req.param('value'), "title":req.param('title')}},
                function(err, record) {
                  record.pivot.counter++;
                  res.redirect(m_pivot.destination);  
                 record.save();
               });
});

Note the pluralization of the query to match the field name in your schema

总以为 2024-11-10 10:01:22

您可以使用嵌入式文档属性进行查询,如下所示:

{'pivot.value': req.param('value')}}

更新以响应评论:

app.get('/:title/:value', function(req, res) {
  Param.findOne({'pivot.value': req.param('value'), "title":req.param('title')}},
                function(err, record) {
                  record.pivot.counter++;
                  res.redirect(m_pivot.destination);  
                 record.save();
               });
});

You can querying using embedded document properties like this:

{'pivot.value': req.param('value')}}

Update in response to comment:

app.get('/:title/:value', function(req, res) {
  Param.findOne({'pivot.value': req.param('value'), "title":req.param('title')}},
                function(err, record) {
                  record.pivot.counter++;
                  res.redirect(m_pivot.destination);  
                 record.save();
               });
});
无所谓啦 2024-11-10 10:01:22

我暂时使用一个简单的 for 循环来解析对象数组来解决它,如下所示:

for (var i=0; i <record.pivots.length; i++){
   if (record.pivots[i].value == req.param('value')){
      res.redirect(record.pivots.destination);
   } 
}

但是,我仍然认为 Mongoose 必须有一种更简单的方式与嵌入文档交互 - 而且这个循环有点慢,特别是当嵌入文档数量增长时大的。

如果有人对在 js 中或使用 mongoose 函数更快地搜索此对象数组有任何建议,请在下面发布。

I solved it temporarily using a simple for loop to parse the object array as follows:

for (var i=0; i <record.pivots.length; i++){
   if (record.pivots[i].value == req.param('value')){
      res.redirect(record.pivots.destination);
   } 
}

However, I still think that Mongoose must have a simpler way of interacting with embedded documents - and this loop is somewhat slow, especially when the number of embedded documents grows large.

If anyone has any suggestions for a faster way to search this object array either in js or with a mongoose function, please post below.

淡看悲欢离合 2024-11-10 10:01:22

最大的问题是,如果您的请求有一些字段为空(应该充当通配符),您将找不到任何内容,因为 mongo 也尝试匹配空参数,因此搜索 {"user":"bob", " color":""} 与 {"user":"bob"、"color":"red"} 或 {"user":"bob"} 不同。这意味着你必须首先创建一个查询对象并在传入之前过滤掉任何未使用的参数,并且如果你创建一个查询对象,你不能再执行类似“user.name=...”的操作,因为 mongo 解释这是一个错误,因为它不会首先将对象文字解析为字符串。
关于这个问题有什么想法吗?

附注您可能认为制作如下对象很容易:
用户名=“鲍勃”; user.color:"绿色";用户.signup.time =“12342561”
然后使用 user 作为查询对象:/

the biggest problem with this is that if your req has some fields empty (that should act as wildcard), you will not find anything since mongo tries to match empty params as well, so searching for {"user":"bob", "color":""} is not the same as {"user":"bob", "color":"red"} or {"user":"bob"}. this means that you have to first create a query object and filter out any unused parameters before you pass it in, and if you create a query object, you can no longer do something like "user.name=..." because mongo interperets this as an error since it does not first resolve the object literal into a string.
Any ideas on this problem?

ps. You'd think it would be easy enough to make an object like:
user.name="bob"; user.color:"green"; user.signup.time="12342561"
and then just use user as a query object :/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文