MongoDB uses mongoose to directly query the Id of sub doc?

  mongodb, question

I have a schema:
This schema has a sub doc called address. after the address data is inserted, address will have its own corresponding _id.

My question is, do you need to find the account first and then traverse the address of the account, or can you find the corresponding address directly through the _id of the 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}
 }]},
 });

First of all, you understandsubDocThe definition of is wrong.subDocShould also be a separateSchema->ModelThe generated instance, in short, needs to have a subdocumentSchema

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,
 
 //The emphasis is here.
 address:   [AdressSchema]
 })

One more word, if you don’tCustom SchemaTypesIf so, the original wording is wrong. And even if defined, attributestypeYou cannot point to an object

address: {
 //This is absolutely wrong
 type: [
 {
 name: { type: String},
 phone: { type: String},
 type: { type: String},
 addr: { type: String}
 }
 ]
 }

Because ..mongooseDefault legalSchemaTypesonString, Number, Array, ObjectId, Mixed ...There must be several in the document. Besides, if you do not define any custom Type, any other value after the type attribute will be reported as an error.

If you do not want to define subdocuments, you can do this 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, // Use adrType instead of your Type here to avoid and retain duplicate names
 addr: String
 }
 }
 )