语境
因此,我们已经从Parse.com迁移到托管的MongoDB数据库。现在,我必须编写一个脚本来直接查询我们的数据库(不使用Parse)。
我正在使用nodejs / mongoose,并且能够检索这些文档。
问题
到目前为止,这是我的架构:
var StorySchema = new mongoose.Schema({
_id: String,
genre: String
});
var ActivitySchema = new mongoose.Schema({
_id: String,
action: String,
_p_story: String /* Also tried: { type: mongoose.Schema.Types.ObjectId, ref: 'Story' } and { type: String, ref: 'Story' }*/,
});
我想编写一个查询,以获取与相关Story(作为指针存储)的这些文档。
Activity
.find({
action: 'read',
})
.exec(function(error, activities) {
activities.forEach(function(activity) {
// I would like to use activity._p_story or whatever the mean to access the story here
});
});
题
假设
_p_story
字段在对象ID之前包含Story$
,是否有办法用它们的故事填充获取的活动?谢谢!
最佳答案
我一直在研究的一个选项是为每个指针创建自定义数据类型的能力。不幸的是,Parse将这些视为“属于”关系,但没有存储Mongoose想要populate()
的“ hasMany”关系。但是一旦到位,您就可以轻松地执行循环以获取相关数据。这不是理想的方法,但是可以正常工作,而且无论如何,这实际上是实际情况。
PointerTypeClass.js->这将用于填充相反的方向。
var Pointer = function(mongoose) {
function PointerId(key, options) {
mongoose.SchemaType.call(this, key, options, 'PointerId');
}
PointerId.prototype = Object.create(mongoose.SchemaType.prototype);
PointerId.prototype.cast = function(val) {
return 'Pointer$' + val;
}
return PointerId;
}
module.exports = Pointer;
还请确保猫鼬通过执行
mongoose.Schema.Types.PointerId = require('./types/PointerTypeClass')(mongoose);
了解新类型最后。如果您愿意编写一些cloudcode,则可以创建ID数组,以便您的填充者了解对象。基本上在Object.beforeSave中,您将更新关系的ID数组。希望这可以帮助。
关于node.js - 查询Parse.com与Mongoose迁移的数据库指针关系,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36600326/