我正在Apollo Server + Express + MongoDB + Mongoose项目上,我有一个Site
模式,其中有两个包含User
引用的属性:owner
和{{1 }}。两者均已保存,但只有users
包含用户数据。
这是猫鼬的模型定义:
owner
这是网站的类型定义:
import mongoose, { Schema } from 'mongoose';
const siteSchema = new Schema({
name: {
type: String,
required: true
},
origins: {
type: [String]
},
owner: {
type: Schema.Types.ObjectId,
ref: 'User'
},
users: {
type: [Schema.Types.ObjectId],
ref: 'User'
},
createdOn: {
type: String
},
updatedOn: {
type: String
}
});
export const Site = mongoose.model('site', siteSchema);
这是我的import { gql } from 'apollo-server-express';
const site = gql`
extend type Site {
id: String
name: String
owner: User
origins: [String]
users: [User]
createdOn: String
updatedOn: String
}
extend type Query {
sites: [Site]
site(id: ID!): Site
}
extend type Mutation {
addSite(name: String!, owner: [String!], origins: [String], users: [String]): Site
updateSite(id: ID!, name: String, owner: [String], origins: [String], users: [String]): Site
deleteSite(id: ID!): Result
}
`;
export default site;
解析器:
updateSite
如果我在分配import { Site } from '../models/Site';
export default {
Mutation: {
updateSite: async (_, args) => {
let site = await Site.findById(args.id)
.populate({
path: 'owner',
model: User
}).populate({
path: 'users',
model: User
})
.exec();
if (!site) {
throw {
success: false,
message: "No existe el sitio"
};
}
site.updatedOn = Date.now();
try {
if (args.name) {
site.name = args.name;
}
if (args.origins) {
site.origins = args.origins;
}
if (args.owners) {
site.owners = args.owners;
}
site.users = args.users;
site = await site.save();
return site;
} catch (e) {
throw e.message;
}
},
}
}
常量之前登录它。它将显示site
和users
对象。但是之后,它将在MongoDB游乐场中显示owner
对象的null
数据,而在IDE控制台中仅显示一个字符串。
我想念什么?任何评论表示赞赏。