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 understand
subDoc
The definition of is wrong.subDoc
Should also be a separateSchema
->Model
The 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’t
Custom SchemaTypes
If so, the original wording is wrong. And even if defined, attributestype
You cannot point to an objectaddress: { //This is absolutely wrong type: [ { name: { type: String}, phone: { type: String}, type: { type: String}, addr: { type: String} } ] }
Because ..mongooseDefault legal
SchemaTypes
onString, 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 } } )