1

I have the schema:

const mongoose = require('mongoose');
const deepPopulate = require('mongoose-deep-populate')(mongoose);
const Schema = mongoose.Schema;

const MessageSchema = new Schema({
  body: String,
  seen: Boolean,
  sender: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User"
  },
  recipient: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User"
  }
}, { timestamps: { createdAt: 'created_at' } });

MessageSchema.plugin(deepPopulate);
module.exports = mongoose.model('Message', MessageSchema);

query:

router.get('/getSentMessages', checkJWT, (req, res, next) => {

      Messages.find({ sender: req.decoded.user._id }).populate('User').exec(function (err, messages) {
        console.log('getSentMessages ', messages);
        res.json({
          success: true,
          messages: messages,
          message: "Successful"
        });
      });

I am getting the ref user being populated in output:

getSentMessages  [
  model {
    '$__': InternalCache {
      strictMode: true,
      selected: {},
      shardval: undefined,
      saveError: undefined,
      validationError: undefined,
      adhocPaths: undefined,
      removing: undefined,
      inserting: undefined,
      version: undefined,
      getters: {},
      _id: 5d6bebd30a78a52ebf5ed574,
      populate: undefined,
      populated: [Object],
      wasPopulated: false,
      scope: undefined,
      activePaths: [StateMachine],
      pathsToScopes: {},
      ownerDocument: undefined,
      fullPath: undefined,
      emitter: [EventEmitter],
      '$options': true
    },
    isNew: false,
    errors: undefined,
    _doc: {
      __v: 0,
      body: 'Your profile',
      sender: 5d6b06eca4b60b09b3c376e1,
      recipient: [model],
      created_at: 2019-09-01T16:03:31.892Z,
      updatedAt: 2019-09-01T16:03:31.892Z,
      _id: 5d6bebd30a78a52ebf5ed574
    },
    '$init': true
  }
]

What went wrong I am not able to figure out?

2 Answers 2

2

You need to call populate on the fields that you want to populate

router.get('/getSentMessages', checkJWT, (req, res, next) => {
  Messages.find({ sender: req.decoded.user._id })
    .populate('sender')
    .populate('recipient')
    .exec(function (err, messages) {
      console.log('getSentMessages ', messages);
      res.json({
        success: true,
        messages: messages,
        message: "Successful"
      });
  });
});
Sign up to request clarification or add additional context in comments.

Comments

0

stringify and parse the result. like JSON.parse(JSON.stringify(messages))

router.get('/getSentMessages', checkJWT, (req, res, next) => {
    Messages.find({ sender: req.decoded.user._id }).populate('User').exec(function (err, messages) {
        console.log('getSentMessages ', JSON.parse(JSON.stringify(messages))); // here
        res.json({
            success: true,
            messages: messages,
            message: "Successful"
        });
    });
}

2 Comments

Still i didnt get the ref object
@kittu are you checking in console or response?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.