【问题标题】:How to get value form nested object in mongoose?如何在猫鼬中从嵌套对象中获取值?
【发布时间】:2016-01-20 02:49:41
【问题描述】:

我在nodejs上有一些使用mongoose模块的代码,我需要获取嵌套值,让我给你看:

我创建架构

var clientScheme = mongoose.Schema({
    name: Object
    address: String,
    number: Number,
    operator: Object,
    services: Object,
    email: String
})

然后我创建模型:

var Client = mongoose.model('Client', clientScheme);

然后进行创建/保存 - 很简单,我只是先向您展示 client.json

   {
        "name":{
             "first":"John",
             "last":"Smith"
              },
        "address":"Avenue 1",
        "number": 7012341,
        "email":"john@gmail.com"
    }

然后,我需要知道这个客户的名字。我尝试:

clients.find({"name":{"first":"John"}})

没用。

怎么了?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    你可以这样做:

    db.clients.find({"name.first":"John"})
    

    【讨论】:

      【解决方案2】:

      你应该使用点符号:

      Client.find({"name.first": "John"}, function(err, clients){
          // your callback body here
      });
      

      【讨论】:

        【解决方案3】:

        它不起作用,因为您试图找到一条“名称”与此完全相同的记录:

        {first: "John"}
        

        但您的客户有姓名:{first: "John", last: "Smith"}

        因此,以下任何查询都会找到您的客户:

        clients.find({"name.first": "John"}) or
        clients.find({"name.last": "Smith"}) or
        clients.find({"name": {first: "John", last: "Smith"}})
        

        希望对你有帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-05-30
          • 1970-01-01
          • 2019-10-26
          • 1970-01-01
          • 2014-02-10
          • 2014-07-13
          • 1970-01-01
          • 2016-08-17
          相关资源
          最近更新 更多