【问题标题】:Query Parse.com migrated database pointer relationship with Mongoose使用 Mongoose 查询 Parse.com 迁移的数据库指针关系
【发布时间】:2016-05-03 00:17:13
【问题描述】:

上下文

所以我们已经从 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$,有没有办法让获取的活动填充他们的故事?

谢谢!

【问题讨论】:

  • 只是评论,但您可以运行自己的解析服务器,而不是重写所有查询。 github.com/ParsePlatform/parse-server。示例应用程序使其变得简单,“解析服务器示例应用程序”部分。
  • 我一直在寻求做同样的事情来绕过一些限制。你能做到吗?

标签: node.js parse-platform mongoose


【解决方案1】:

我一直在研究的一个选项是为每个指针创建自定义数据类型的能力。不幸的一面是 Parse 将这些视为 'belongsTo' 关系,但不存储 Mongoose 想要的 populate() 的 'hasMany' 关系。但是一旦这到位,您就可以轻松地执行循环来获取关系数据。不理想,但可以工作,而且无论如何 populate 在幕后确实在做。

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 通过 mongoose.Schema.Types.PointerId = require('./types/PointerTypeClass')(mongoose); 了解新类型

最后。如果您愿意编写一些云代码,您可以创建 id 数组以供您的填充了解对象。基本上在您的 Object.beforeSave 中,您将更新关系的 id 数组。希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多