我尝试通过Mongoose populate.为某个用户调用相关的日志列表谁能帮我完成回复?
这些是计划:
const logSchema = new Schema({
logTitle: String,
createdOn:
{ type: Date, 'default': Date.now },
postedBy: {
type: mongoose.Schema.Types.ObjectId, ref: 'User'}
});
const userSchema = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
}
logs: { type: mongoose.Schema.Types.ObjectId, ref: 'logs' }
});
mongoose.model('User', userSchema);
mongoose.model('logs', logSchema);

const userReadLogs = function (req, res) {
if (req.params && req.params.userid) {
User1
.findById(req.params.userid)
.populate('logs')
.exec((err, user) => {
if (!user) { }); // shortened
return;
} else if (err) {
return; // shortened
}
response = { //question
log: {
user: user.logs
}
};
res
.status(200)
.json(response);
});
} else { }); //
}
};

Postman等的回应是这样的:
{
"log": {5a57b2e6f633ce1148350e29: logTitle1,
6a57b2e6f633ce1148350e32: newsPaper44,
51757b2e6f633ce1148350e29: logTitle3
}

答案 0 :(得分:0)
首先,logs
不是日志列表;它将是object
。如果您想为每个用户提供多个日志,则需要将其存储为array
:logs: [{ type: mongoose.Schema.Types.ObjectId, ref: 'logs' }]
从Mongoose
文档:“已填充的路径不再设置为其原始_id,它们的值将替换为从数据库返回的mongoose文档,方法是在返回结果之前执行单独的查询。 / em>“换句话说,在query
user.logs
中,每位用户都会logs
document
。它将包含properties
,logTitle
,createdOn
和postedBy
中的所有user.logs
。
从服务器发送json
为res.json(user.logs)
就像:const userReadLogs = function (req, res) {
if (req.params && req.params.userid) {
User1
.findById(req.params.userid)
.populate('logs')
.exec((err, user) => {
if (!user) { }); // shortened
return;
} else if (err) {
return; // shortened
}
res.status(200).json(user.logs)
});
} else { }); //
}
};
一样简单。所以你的查询看起来像这样:
myHeading1 = {};
myHeading1[DocumentApp.Attribute.FONT_SIZE] = 24;
myHeading1[DocumentApp.Attribute.FONT_FAMILY] = "Georgia";
myHeading2 = {};
myHeading2[DocumentApp.Attribute.FONT_SIZE] = 16;
myHeading2[DocumentApp.Attribute.FONT_FAMILY] = "Verdana";
myHeading2[DocumentApp.Attribute.FOREGROUND_COLOR] = "#555555";
var body = DocumentApp.getActiveDocument().getBody();
body.setHeadingAttributes(DocumentApp.ParagraphHeading.HEADING1, myHeading1);
body.setHeadingAttributes(DocumentApp.ParagraphHeading.HEADING2, myHeading2);
我希望这会让它更清晰一点!