我想使用deep-populate插件进行mongoose查询。我肯定没有经验,但是,我没有成功地深入了解某些事情。 这是我的计划:
var mongoose = require('mongoose');
var MMAnswersSchema = new mongoose.Schema({
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
item: { type: mongoose.Schema.Types.ObjectId, ref: 'MMItem'},
answer: [
{
skalaAnswer: Number,
freitextAnswer: String,
multipleChoiceAnswer: String,
answered_at: { type: Date, required: true, default: Date.now }
}
],
last_answered: { type: Date, required: true, default: Date.now }
});
MMAnswersSchema.pre('save', function(next) {
this.last_answered = Date.now;
next();
});
mongoose.model('MMAnswer', MMAnswersSchema);
var deepPopulate = require('mongoose-deep-populate')(mongoose);
MMAnswersSchema.plugin(deepPopulate);
我是否将deepPopulate需要的东西放在正确的位置?
我现在用这条路来获取我的东西:
// Alle Antworten des aktuellen Users laden
// Verwendet von der Historie
.get('/mm-answers/:user_id/get-all-answers', function (req, res, next) {
Answer.find({user:req.params.user_id}, function (err, answer) {
if(err){
return next(err);
}
res.json(answer);
})
.deepPopulate('item')
})
我希望它用实际项替换id,并且项本身包含'ofBox'字段,我也想用实际的box文档替换(这就是为什么我使用deep-populate)。 使用上面的查询根本不会给我任何结果。我仍然在项目字段中有ID。 如果我运行标准.populate('item')命令,它会将项目ID替换为项目本身,但遗憾的是不是项目中的ofBox ID。 (这就是为什么我需要深入填充)。
有人可以帮我解决一下吗?我想我在正确导入/注册插件时犯了一个错误......-.-
答案 0 :(得分:0)
您需要在执行查询之前进行deepPopulate
调用,如下所示:
// Alle Antworten des aktuellen Users laden
// Verwendet von der Historie
.get('/mm-answers/:user_id/get-all-answers', function (req, res, next) {
Answer.find({ user: req.params.user_id }).deepPopulate('item').exec(function (err, answer) {
if (err) {
return next(err);
}
res.json(answer);
});
});

答案 1 :(得分:0)
在模型中,您只需要添加添加插件时要填充的字段:
const mongoose = require('mongoose');
const deepPopulate = require('mongoose-deep-populate')(mongoose);
const MMAnswersSchema = new mongoose.Schema({
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
item: { type: mongoose.Schema.Types.ObjectId, ref: 'MMItem'},
answer: [
{
skalaAnswer: Number,
freitextAnswer: String,
multipleChoiceAnswer: String,
answered_at: { type: Date, required: true, default: Date.now }
}
],
last_answered: { type: Date, required: true, default: Date.now }
});
MMAnswersSchema.pre('save', function(next) {
this.last_answered = Date.now;
next();
});
MMAnswersSchema.plugin(deepPopulate, {
populate: {
user: {
select:'_id name lastName'
},
item: {
select:'_id name'
},
});
const MMAnswers = mongoose.model('answers',MMAnswersSchema);
module.exports = { MMAnswers };
最后,当您需要使用较深的人口时,只需添加您想填充的任何字段
await MMAnswers.findOne({your search}).deepPopulate('user').exec();
或
await MMAnswers.findOne({your search}).deepPopulate('user item').exec();