[英]Mongoose populate not working as expected
我在使用mongoose方面非常新,并且在mongodb上完成了简单的数据库工作。
看到我的用例后,我发现了使用mongoose在mongodb中执行此操作的方法。 但是,我没有得到教程所示的预期结果。
我的模式
var EventsSchema = new mongoose.Schema({
root: {type: mongoose.Schema.Types.ObjectId, ref: 'root'},
voting: [{type: mongoose.Schema.Types.ObjectId, ref: 'Voting'}]
});
var VotingSchema = new mongoose.Schema({
events: {type: mongoose.Schema.Types.ObjectId, ref: 'Events'},
title: {
type: String,
required: true
}
})
var Events = mongoose.model('Events', EventsSchema, 'event');
var Voting = mongoose.model('Voting', VotingSchema, 'voting');
我最初有这两种模式。 我想创建一个投票活动。 创建投票事件后,应在voting schema
中将事件ID按照建议的方式存储,而我想要的是表决事件引用应存储在EventSchema
。
var events = new Events({});
events.save()
.then((events) => {
var voting = new Voting({ events: events._id, title: "Test Title" });
voting.save()
.then((voting) => {
Voting.findOne({title: 'Test Title'})
.populate('events')
.exec(function(err, voting){
console.log(voting, err);
if(err) res.sendStatus(401).send();
else res.sendStatus(200).send();
})
})
.catch((e) => {
res.sendStatus(401).send();
});
})
.catch((e) => {
res.sendStatus(401).send();
})
我在控制台上得到的是
{
_id: 5b83eca82a3cfb1dec21ddc9,
events: { voting: [], _id: 5b83eca82a3cfb1dec21ddc8, __v: 0 },
title: 'Test Title',
__v: 0
}
我的MongoDB看起来像这样
表决
{
"_id" : ObjectId("5b83eca82a3cfb1dec21ddc9"),
"events" : ObjectId("5b83eca82a3cfb1dec21ddc8"),
"title" : "Test Title",
"__v" : 0
}
事件
{
"_id" : ObjectId("5b83eca82a3cfb1dec21ddc8"),
"voting" : [],
"__v" : 0
}
我不确定我的mongodb会是什么样子。 但是一旦尝试了代码,它看起来就像上面一样。
我一定在做错事或错过了重要的事情。 但是文档中也有这种代码。 docs链接 。 帮助我解决此问题。
谢谢
ObjId的数组应在模式中以这种方式定义:
var EventsSchema = new mongoose.Schema({
root: {type: mongoose.Schema.Types.ObjectId, ref: 'root'},
voting: {type: [mongoose.Schema.Types.ObjectId], ref: 'Voting'}//**array bracers**
});
同样在数组类型的字段(如root字段)上调用填充将在API的资源中返回一个空数组,请参见mongoose.set('debug', true);
查询mongoose.set('debug', true);
您会注意到猫鼬在事件模型中搜索的不是root。
尽管您必须在填充方法中告诉猫鼬要使用哪种模型才能使种群起作用,除非您告诉猫鼬要搜索哪种模型。
populate({path:'vooting',model:'vooting'})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.