poncho
poncho

Reputation: 1150

Mongoose is not returning all fields in the document using a simple find()

I have the following Schema:

let User = new Schema({
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  firstName: {
    type: String,
    required: false
  },
  lastName: {
    type: String,
    required: false
  },
  templates: {
    type: Schema.Types.ObjectId,
    ref: 'TemplateInstance',
    required: false
  }
},{
  collection: 'users',
  timestamps: true
});

And the following Mongoose code:

exports.getUsers = (req, res) => {
  User.find((err, users) => {
    if(err)
      return res.status(400).json( { 'users_get_all': 'failure', 'err': err } );
    return res.status(200).json( { 'users_get_all': 'success', 'users': users } );
  });
};

Initially, each user Document does not have anything in the 'templates' field because after the user creates their account, that's when they get to attach templates to it. I have manually added some Template ObjectIDs to the 'templates' field of some users but when I run the getUsers() function, the user documents are returned but with no 'templates' field:

{"users_get_all":"success","users":[{"_id":"5b39f9da294d041b58f97cb3","email":"[email protected]","password":"password","firstName":"firstName","lastName":"lastName","createdAt":"2018-07-02T10:09:30.400Z","updatedAt":"2018-07-02T10:21:34.579Z","__v":0},{"_id":"5b39ff5723d93c17bc00eabf","email":"[email protected]","password":"password","firstName":"firstName2","lastName":"lastName2","createdAt":"2018-07-02T10:32:55.308Z","updatedAt":"2018-07-02T10:32:55.308Z","__v":0}]}

If I look at the MongoDB in something like Studio 3T, the templates array definitely has ObjectIDs in it that refer to Templates in the Template collection.

Screenshot of Studio 3T showing Users collection

Any idea why the 'templates' field is not being returned?

Upvotes: 2

Views: 4718

Answers (1)

Harshal Yeole
Harshal Yeole

Reputation: 4983

Update your schema as follows:

let User = new Schema({
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  firstName: {
    type: String,
    required: false
  },
  lastName: {
    type: String,
    required: false
  },
  templates: [{
    type: Schema.Types.ObjectId,
    ref: 'TemplateInstance',
    required: false
  }]
},{
  collection: 'users',
  timestamps: true
});

As in database, you have templates in the array and you were declaring it an object in the schema.

Upvotes: 5

Related Questions