MongoDB 使用mongoose直接查询sub doc 的Id?
PHP中文网
PHP中文网 2017-05-02 09:19:25
0
1
671

我有一个schema:
这个schema有一个sub doc 叫address,插入address数据之后,address会自己有一个对应的_id.

我的问题是,每次查询这个address的时候,是否需要首先找到这个account,然后遍历account的address,或者可以直接通过address的_id来找到对应的address?

  var AccountSchema = new mongoose.Schema({
    email:     { type: String, unique: true },
    password:  { type: String},
    phone:     { type: String},
    name:      {type: String},
    address:   {type: [{
      name: { type: String},
      phone: { type: String},
      type: { type: String},
      addr: { type: String}
    }]},
  });
PHP中文网
PHP中文网

认证0级讲师

reply all(1)
给我你的怀抱

First you understand subDoc 的定义就错了, subDoc 应该也是一个由单独的 Schema -> Model 生成的实例, 简单来说, 就是得有一个子文档的 Schema

const AdressSchema = new mongoose.Schema({
      name: String,
      phone: String,
      type: String,
      addr: String
    })

const AccountSchema = new mongoose.Schema({
    email:     { type: String, unique: true },
    password:  String,
    phone:     String,
    name:      String,
    
    //重点在这里
    address:   [AdressSchema]
  })

One more thing, if you don’t have 自定义的 SchemaTypes的话, 原来的写法就是错的. 而且就算定义了, 属性type you can’t point to an object

address: {
    //这样就是绝对错误 
    type: [
        {
            name: { type: String},
            phone: { type: String},
            type: { type: String},
            addr: { type: String}
        }
    ]
}

Because mongoose is legal by default SchemaTypesSchemaTypesString, Number, Array, ObjectId, Mixed... just String, Number, Array, ObjectId, Mixed...

There must be a few in the document. Except In addition, if you do not define any custom Type, any other value after the type attribute will result in an error.

If you don’t want to define a subdocument, you can do as follows:🎜
const AccountSchema = new mongoose.Schema({
    email:     { type: String, unique: true },
    password:  String,
    phone:     String,
    name:      String,
    address:   {
        name: String,
        phone: String,
        adrType: String,        //这里用 adrType 替代你的 type, 避免和保留字重名
        addr: String
    }
  }
)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!