Miguel Stevens
Miguel Stevens

Reputation: 9211

Mongoose Populate ignored for this basic setup

I have a User Schema, which has multiple notes, and the Note which belongs to a userId

const UserSchema = new Schema({
    _id: Schema.Types.ObjectId,
    email: {type: String, required: true, trim: true, lowercase: true, unique: true},
    notes: [{type: Schema.Types.ObjectId, ref: 'Note'}]
});

const NoteSchema = new Schema({
    userId: {type: mongoose.Types.ObjectId, ref: 'User'},
    content: {type: String, required: true, trim: true, lowercase: true},
});

I'm trying to populate my User with the notes using the following syntax (from the docs)

const user = await User.findById(mongoose.Types.ObjectId("5bd2a8c4963ac00f57a18074"))
    .populate('notes')
    .exec(function (err, result) {
        console.log(result);
    });

But it's returning the User without the Notes data. Any idea what I might be doing wrong?

Upvotes: 0

Views: 63

Answers (1)

Hardik Shah
Hardik Shah

Reputation: 4210

NoteSchema here is the problem:

userId: {type: mongoose.Types.ObjectId, ref: 'User'}

Use below,

userId: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}
// OR
userId: {type: Schema.Types.ObjectId, ref: 'User'}
// OR
userId: {type: Schema.ObjectId, ref: 'User'} // For backword compatibility

Note:- The schema should always use mongoose.Schema.Types. And mongoose.Types.ObjectId can be used withing mongoose implementation.

I am able to get document properly (Below code):

var mongoose = require('mongoose'),
Schema = mongoose.Schema;


const NoteSchema = new Schema({
    userId: {type: Schema.Types.ObjectId, ref: 'UserTest'},
    content: {type: String, required: true, trim: true, lowercase: true},
});

const UserSchema = new Schema({
  _id: Schema.Types.ObjectId,
  email: {type: String, required: true, trim: true, lowercase: true, unique: true},
  notes: [{type: Schema.Types.ObjectId, ref: 'NoteTest'}]
});

var Note = mongoose.model('NoteTest', NoteSchema);
var User = mongoose.model('UserTest', UserSchema);


User.find({_id : mongoose.Types.ObjectId("5bd2c84dd79cc5d8b1c62964")})
  .populate('notes')
  .exec(function (err, result) {
      console.log("result.....", JSON.stringify(result));
  });

Output:

[
  {
    "_id": "5bd2c84dd79cc5d8b1c62964",
    "email": "[email protected]",
    "notes": [
      {
        "_id": "5bd2c869d79cc5d8b1c62965",
        "content": "ABC",
        "userId": "5bd2c84dd79cc5d8b1c62964"
      },
      {
        "_id": "5bd2c88ad79cc5d8b1c62966",
        "content": "DEF",
        "userId": "5bd2c84dd79cc5d8b1c62964"
      }
    ]
  }
]

Upvotes: 1

Related Questions