Dynamoose中Publication关联User数据填充失败求助
我正在构建一个API,允许用户发布内容展示在线程中,希望获取Publication时能同时获取作者(User)的数据,例如通过console.log( publication.author.completeName )访问。保存Publication时,author字段存储的是发布者的User ID,参考Dynamoose v1文档尝试使用populate方法填充该字段,但填充失败,author字段仍仅显示ID字符串。
相关代码
User模型
const dynamoose = require("dynamoose"); const { v4: uuidv4 } = require('uuid'); const userSchema = new dynamoose.Schema( { id: { type: String, hashKey: true, default: () => uuidv4(), }, email: { type: String, required: true }, completeName: { type: String, }, pseudo: { type: String, // Should make check on create and edit to ensure unicity of this column }, gender: { type: String, enum: ['male', 'female', 'other'] }, speciality: { type: String }, address: { type: String, }, phoneNumber: { type: String, } }, { timestamps: true } ); module.exports = dynamoose.model("User", userSchema);
Publication模型
const dynamoose = require("dynamoose"); const { v4: uuidv4 } = require('uuid'); const publicationSchema = new dynamoose.Schema( { id: { type: String, hashKey: true, default: () => uuidv4(), }, photo: { type: Array, schema: [String], default: [] }, description: { type: String, required: true }, anatomies: { type: Array, schema: [String], required: true, }, specialities: { type: Array, schema: [String], required: true, }, groupId: { type: String, }, author: { type: String } }, { timestamps: true } ); module.exports = dynamoose.model("Publication", publicationSchema);
查询代码
exports.listPublication = async (req, res, next) => { try { Publication .scan() .exec() .then( async function (data) { return Promise.all( data.map(function(pub){ return pub.populate({ path: 'author', model: 'User' }); })) }) .then((data) => { success(res, { data: data }); }) .catch((err) => { throw new HttpException(err.message); }); } catch (err) { error(next, res, err); } }
解决方案
1. 修改Publication Schema的author字段定义
Dynamoose的populate功能需要明确字段与关联模型的关系,原代码中author只是普通String类型,无法触发关联查询。需要将其修改为带引用的类型:
// 修改后的Publication Schema中author字段 author: { type: dynamoose.Schema.Types.String, ref: 'User' // 指定关联的User模型 }
2. 优化查询代码
Dynamoose v1支持在查询链中直接调用populate,无需手动遍历处理,代码更简洁高效:
exports.listPublication = async (req, res, next) => { try { const data = await Publication.scan().populate('author').exec(); success(res, { data: data }); } catch (err) { error(next, res, new HttpException(err.message)); } }
原因说明
- 未指定
ref属性时,Dynamoose无法识别author字段需要关联User模型,因此populate操作不会生效,仅返回原始ID字符串。 - 直接在查询链中调用
populate是Dynamoose推荐的用法,内部会批量处理关联查询,性能比手动遍历调用更优。
内容的提问来源于stack exchange,提问作者Tiny Skillz
相关产品推荐
相关产品推荐

