如何用Mongoose正确实现含两种嵌套Schema的数组以存储Google评论API数据?
解决Mongoose存储Google评论API数据的嵌套结构问题
你在使用Mongoose存储Google评论API数据时遇到两个问题:
- 部分插入对象存在空字段,数组中的嵌套Key-Value无法被正确捕获
- 第二种Schema写法出现
ReferenceError: Cannot access 'LastModifiedSchema' before initialization错误
问题原因
- 结构不匹配:第一个Schema将
userComment、developerComment设为顶层字段,但API返回的是comments数组,数组元素包含userComment/developerComment子对象,导致数据无法映射,出现空字段。 - 变量初始化顺序错误:第二个Schema中,
DeveloperCommentSchema引用了还未定义的LastModifiedSchema,触发引用错误。 - 字段缺失:两个Schema都未定义API返回中的
deviceMetadata、appVersionName等字段,导致这些数据无法被存储。
正确实现方案
按从底层到顶层的顺序定义子Schema,确保引用时变量已初始化,同时严格匹配API的数据结构:
const mongoose = require("mongoose"); // 定义时间戳子Schema const LastModifiedSchema = new mongoose.Schema({ seconds: { type: String, default: '' }, nanos: { type: Number, default: 0 }, }); // 定义设备元数据子Schema const DeviceMetadataSchema = new mongoose.Schema({ productName: { type: String, default: '' }, manufacturer: { type: String, default: '' }, deviceClass: { type: String, default: '' }, screenWidthPx: { type: Number, default: 0 }, screenHeightPx: { type: Number, default: 0 }, nativePlatform: { type: String, default: '' }, screenDensityDpi: { type: Number, default: 0 }, glEsVersion: { type: Number, default: 0 }, ramMb: { type: Number, default: 0 }, }); // 用户评论子Schema const UserCommentSchema = new mongoose.Schema({ text: { type: String, default: '' }, lastModified: { type: LastModifiedSchema, default: () => ({}) }, starRating: { type: Number, default: 0 }, reviewerLanguage: { type: String, default: '' }, device: { type: String, default: '' }, androidOsVersion: { type: Number, default: 0 }, appVersionCode: { type: Number, default: 0 }, appVersionName: { type: String, default: '' }, deviceMetadata: { type: DeviceMetadataSchema, default: () => ({}) }, thumbsUpCount: { type: Number, default: 0 }, thumbsDownCount: { type: Number, default: 0 }, }); // 开发者评论子Schema const DeveloperCommentSchema = new mongoose.Schema({ text: { type: String, default: '' }, lastModified: { type: LastModifiedSchema, default: () => ({}) }, }); // 主评论Schema const ReviewSchema = new mongoose.Schema({ reviewId: { type: String, default: '', unique: true }, authorName: { type: String, default: '' }, // 匹配API的comments数组结构 comments: [{ userComment: { type: UserCommentSchema, default: null }, developerComment: { type: DeveloperCommentSchema, default: null } }], appInformation: { packageIdentifier: { type: String, default: '' } } }); const Review = mongoose.model("Review", ReviewSchema); module.exports = Review;
数据插入说明
API返回的reviews数组结构与Schema完全匹配,可直接传入插入方法:
// 假设apiData是API返回的完整数据 const apiData = { /* 你的API返回数据 */ }; Review.insertMany(apiData.reviews) .then(() => console.log("数据插入成功")) .catch(err => console.error("插入失败:", err));
内容的提问来源于stack exchange,提问作者ytpm
相关产品推荐
相关产品推荐

