【问题标题】:Mongoose one has many relations between SchemasMongoose 的 Schema 之间有很多关系
【发布时间】:2015-05-20 14:08:56
【问题描述】:

我知道这个问题之前已经提出过很多次,而且 Mongo 没有那种确切的“有很多”联系,但到目前为止我未能在两个模式之间建立联系。这是我所拥有的:

用户模型(user.js)

var userSchema = mongoose.Schema({

    posts: {
        _id : { type: Schema.Types.ObjectId, ref: 'Post' },
        title : {type: String, ref: 'Post'}
    },

    facebook         : {
        id           : String,
        token        : String,
        email        : String,
        name         : String
    }
});  

并发布架构(post.js)

var meetingsSchema = mongoose.Schema({
    title: String,
    description: String,
    _owner: { type: Schema.Types.ObjectId, ref: 'User' },
    ownerName: { type: String, ref: 'User' },
    created_at: { type: Date, default: Date.now },
});

我使用模式填充,它与 post 完美配合:它们每个都有所有者。但是,它不适用于用户。我希望能够检索显示属于他们的帖子的用户列表。在 routes.js 我定义了一个对数据库的 api 调用

app.get('/api/users', function(req, res) {
    User.find(function(err, users) {
        if (err)
            res.send(err)
        res.json(users); 
    }).populate('posts._id', 'posts.title');
});

但是,无论是在 shell 中还是在客户端 user.posts 中(毫不奇怪)都返回空数组。如何正确绑定这两个模型?

【问题讨论】:

    标签: mongoose mongoose-populate


    【解决方案1】:

    您指向用户“帖子”的链接不是数组吗?所以只链接一个帖子?

    【讨论】:

      【解决方案2】:

      只是一个疯狂的猜测。

      1. User.find所有用户。
      2. 然后您将它们全部归还。
      3. 然后您填充帖子 ID 和标题,这已经为时已晚,因为您已经发送了用户。

      查看人口示例here

      此外,我希望.posts 属性是一个数组,而不仅仅是平面对象。参见comments 属性here

      【讨论】:

        猜你喜欢
        • 2015-04-07
        • 2013-07-11
        • 1970-01-01
        • 1970-01-01
        • 2023-03-11
        • 1970-01-01
        • 2019-02-01
        • 2017-10-23
        • 2014-07-10
        相关资源
        最近更新 更多