1

I try to associate a chat message with an user. But the populate function gives me an user undefined

//message.js
module.exports = {

  attributes: {

    user:{
      model: 'User'
    },
    message:{
      type:'string',
      required:true
    }
  }

};

I save an entry of a message and try to populate the messages with the user afterward

module.exports = {

  test: function(req, res){

    var data = {
      user : "5533b9f00fe12ff020c67225",
      message : 'auto generated'
    };

    Message.create(data, function messageCreated(err, message){

      if(err) return res.negotiate(err);

          Message.find().populate('user').exec(function(err, messages){
            if(err) return res.negotiate(err);

            res.json(messages);

          });

      });

  }

};

But it always gives me user undefined back, when I try to populate.

What I have tried so far:

  • get one user and populate all his messages: works!
  • find one user according the found Message's associated userId the step before, to ensure the user exists: works!
  • change the Assosiation so another Message instead of an User and than populate the Messages with the one "master message" : works!

I don't understand why it works with other models but not the User model

Cyril CHAPON
  • 3,556
  • 4
  • 22
  • 40
klanm
  • 3,168
  • 3
  • 19
  • 22
  • your user id is correct ? User exist in DB ? – jaumard Apr 19 '15 at 14:48
  • yes I also tried to get the user after the message from the message's user id and it worked – klanm Apr 19 '15 at 15:08
  • 1
    Show us your User model maybe there is a problem with it (your association with Message model) – jaumard Apr 19 '15 at 15:17
  • 1
    with other models as association It worked without the other association side, but here is my message assosiation from my user anyway: messages: { collection: 'Message', via: 'user' }, – klanm Apr 19 '15 at 15:21
  • You can try to add dominant: true – jaumard Apr 19 '15 at 15:23
  • what is your PK in your message model? And you might want to show the relevant parts of your user model as well. – Meeker Apr 19 '15 at 19:48
  • My Pk is the Mongodb Id. I have read that it would make some problems in similar cases. But I cannot simply change my Pk, the app is too big – klanm Apr 19 '15 at 20:35
  • Could I iterate trough each retrieved message model and find() the according user model? Or are there too many database operations then. Doesn't populate use the same amount of operations? Thank you – klanm Apr 19 '15 at 20:42
  • Does `Message.find()` return values (IDs) for `user` key without using `populate('user')`? – Nazar Apr 19 '15 at 22:32
  • yes without populate('user') , i get the user's ID stored in user – klanm Apr 20 '15 at 00:44
  • Can you please include your users model so that we can take a look at it. – avian Apr 23 '15 at 08:19

0 Answers0