我正在使用Mongoose,并且在尝试填充子文档时遇到问题。
我在Mongoose中设计了3种模型:客户,联系人和组。 客户拥有多个联系人和组。该群组拥有一些联系人。
这是我的模特:
import Mongoose from "../services/Mongoose";
import {ContactSchema, IContact} from "./Contact";
import {GroupSchema, IGroup} from "./Group";
export interface IAccount extends Mongoose.Document {
contacts: Mongoose.Types.DocumentArray<IContact>
groups: Mongoose.Types.DocumentArray<IGroup>
}
export const AccountSchema = new Mongoose.Schema({
contacts: [ContactSchema],
groups: [GroupSchema],
});
const Account = Mongoose.model<IAccount>('Account', AccountSchema);
export default Account;
import Mongoose from "../services/Mongoose";
export interface IContact extends Mongoose.Document {
lastName: string
firstName: string
}
export const ContactSchema = new Mongoose.Schema({
lastName: {type: String, default: ""},
firstName: {type: String, default: ""},
});
const Contact = Mongoose.model<IContact>('Contact', ContactSchema);
export default Contact;
import Mongoose from "../services/Mongoose";
import {IContact} from "./Contact";
import {Schema} from "mongoose";
export interface IGroup extends Mongoose.Document {
name: string
comments: string
contacts: IContact["_id"][]
}
export const GroupSchema = new Mongoose.Schema({
name: {type: String},
comments: {type: String, default: ""},
contacts: [{type: Schema.Types.ObjectId, ref: "Contact"}]
});
const Group = Mongoose.model<IGroup>('Group', GroupSchema);
export default Group;
当我要填充Account.Groups.Contacts时会发生此问题。
//With this query, I can see all the contacts' ObjectId in the groups.contacts property.
const account = await Account.findById(res.locals.accountId);
//However, with this one, contacts property in groups is an empty array.
const account = await Account.findById(res.locals.accountId).populate("groups.contacts").exec();
如何正确填充帐户的路径组。联系人?
预先感谢您的贡献。