【问题标题】:Meteor and Mongo DB delivers different results when doing findOne() on a ArrayMeteor 和 Mongo DB 在数组上执行 findOne() 时会提供不同的结果
【发布时间】:2015-08-13 11:22:15
【问题描述】:

我有一个集合,其中包含一组对象(我只是在其中放了一些字段,架构运行良好)。

收藏联系人:

title: {
    type: String,
    label: "Title",
    max: 200
},
adresses: {
    type: [Object],  
    optional: true
     },
"adresses.$.id": {
    type: String,
    label: "ID"
},
"adresses.$.street": {
    type: String,
    label: "street",
    decimal: true,
    optional: true
}

当我做一个:

 db.contacts.findOne({_id:  "59gXADmH9GLNDjELo"}, {adresses: {$elemMatch: 
   {id: "xpdYRKGGjHJLnCevM"}}});

在 Mongo DB 控制台上,它返回:

{
  "_id" : "59gXADmH9GLNDjELo",
  "adresses" : [
    {
      "id" : "xpdYRKGGjHJLnCevM",
      "street" : "FakeStreet123"            
    }
  ]
}

如我所愿 - 只需返回数组的 1 个元素。

当我在 Meteor(浏览器控制台)上做同样的事情时:

Contacts.findOne({_id:  "59gXADmH9GLNDjELo"}, {adresses: {$elemMatch:
  {id: "xpdYRKGGjHJLnCevM"}}});

我得到了数组的所有元素。如何解决这个问题?我希望得到与 Mongo DB 相同的结果。

【问题讨论】:

    标签: arrays mongodb meteor


    【解决方案1】:

    您可以使用._find() 下划线方法来检索您想要的文档:

    var doc = Contacts.findOne(
            {_id:  "59gXADmH9GLNDjELo"}, 
            {adresses: {
                $elemMatch: {id: "xpdYRKGGjHJLnCevM"}
            }
        }),
        address = _.find(doc.adresses, function(address) {
                      return address._id === "xpdYRKGGjHJLnCevM"
                 });
    

    【讨论】:

      猜你喜欢
      • 2016-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2020-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多