问题描述
我有一个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} }]}, });
问题解答
回答1:首先你理解的 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] })
另外多说一句, 如果你没有自定义的 SchemaTypes的话, 原来的写法就是错的. 而且就算定义了, 属性type也不可以指向一个对象
address: { //这样就是绝对错误 type: [{ name: { type: String}, phone: { type: String}, type: { type: String}, addr: { type: String}} ]}
因为 mongoose 默认的合法 SchemaTypes 就 String, Number, Array, ObjectId, Mixed... 那么几个, 文档里肯定有. 除此以外, 如果你没有定义任何自定义 Type, 那在 type 属性后面任何其他的值都是会报错的.
如果你不想定义子文档,你可以像下面这样做:
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 } })

