0

I know that this question has been raised many times before and that Mongo doesn't have that exact "has many" connection, but I failed to make connections between two schemas so far. Here is what I have:

User model (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
    }
});  

And posts schema (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 },
});

I use schema population and it works perfect with post: each one of them has owner. However, it doesn't work that well with users. I want to be able to retrieve list of users showing posts that belong to them. In routes.js I defined an api call to database

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');
});

But, both in shell and (not surprisingly) on clientside user.posts returns empty array. How can I bind these two models correctly?

Stennie
  • 63,885
  • 14
  • 149
  • 175
vitalym
  • 893
  • 6
  • 12
  • 29

2 Answers2

0

Just a wild guess.

  1. You User.find all the users.
  2. Then you return them all.
  3. Then you populate post ID and title, which is already too late because you sent the users already.

See the population examples here.

Additionally, I expect the .posts property to be an array, not just plane object. See comments property here.

Vasyl Boroviak
  • 5,959
  • 5
  • 51
  • 70
0

Your link to "posts" on user is not an array? So only linking one post?

Tony Gutierrez
  • 753
  • 1
  • 6
  • 16