node.js - Mongoose populate not working as expected
问题描述
I am very much new in using mongoose and had done simple db work on mongodb.
Seeing my usecase I found this method of doing it in mongodb using mongoose. However I am not getting expected result as shown in tutorials.
My Schemas
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');
I have these two schemas initially. I want to create a voting event. When voting event is created then in voting schema
events id should be stored as suggested and more I want is that voting event reference should be stored in 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();
})
What I am getting on console is
{
_id: 5b83eca82a3cfb1dec21ddc9,
events: { voting: [], _id: 5b83eca82a3cfb1dec21ddc8, __v: 0 },
title: 'Test Title',
__v: 0
}
My MongoDB looks like this
voting
{
"_id" : ObjectId("5b83eca82a3cfb1dec21ddc9"),
"events" : ObjectId("5b83eca82a3cfb1dec21ddc8"),
"title" : "Test Title",
"__v" : 0
}
events
{
"_id" : ObjectId("5b83eca82a3cfb1dec21ddc8"),
"voting" : [],
"__v" : 0
}
I am not sure how will my mongodb look like. But after attempting the code once it looks like above.
I must be doing something wrong or missing something important. But this kind of code is there in docs too. docs link. Help me in sorting this issue.
Thanks
解决方案
ObjIds 数组应该在模式中以这种方式定义:
var EventsSchema = new mongoose.Schema({
root: {type: mongoose.Schema.Types.ObjectId, ref: 'root'},
voting: {type: [mongoose.Schema.Types.ObjectId], ref: 'Voting'}//**array bracers**
});
同样在数组类型的字段(如 root 字段)上调用 population 将在 API 的 res 中返回一个空数组,查看mongoose.set('debug', true);
您命中的查询会注意到 mongoose 在事件模型中搜索而不是 root。
尽管您必须在人口方法中告诉猫鼬要使用哪个模型才能使人口正常工作,除非您告诉猫鼬要在哪个模型中搜索。
populate({path:'vooting',model:'vooting'})
推荐阅读
- python - 将 dict 转换为具有更高级别的数据帧
- c++ - 我将如何平衡退化的树?C++ 数据结构
- swift - switch 语句:在 swift 中从 if 语句转换为 switch 语句
- javascript - 我正在尝试使用 AJAX 或 req.body 为 NODEJS 获取变量
- ios - 关于 Swift 中的 Copy 的问题
- python - 使用 BeautifulSoup 在 Python 中抓取缺货通知程序
- c - linux服务器C中未读取文件中的数据
- c# - SQL 空间数据类型的实体框架核心支持 - DBGeography?
- ios - 在 NativeScript 中访问 iOS 通用链接中的查询参数
- javascript - Google Earth Engine - 连接“年份”以迭代函数