简体   繁体   中英

Mongoose JS - Populate method not returning full referenced object… - Only returning objectId version

When I use the populate method, I am still only getting the _id.

Here is the controller I want this to take place in:

show: function(req, res) {
User.findOne({
  _id: req.params.id
})
.populate("roommates")
.exec(function(err, user) {
  if (err) {
    console.log(err);
  } else {
    res.json(user.roommates)
  }
})

}

Here is my User model, with roommates reference at the very bottom:

var UserSchema = new Schema({
  name: String,
  username: {
    type: String,
    required: [true, "Please enter a username"],
    minlength: [6, "Username must be at least 6 characters"],
    maxlength: [15, "Username cannot exceed 15 characters"],
    unique: true
  },
  password: {
    type: String,
    required: [true, "Please enter a password"],
    minlength: [6, "Password must be at least 6 characters"],
    maxlength: [17, "Password cannot exceed 17 characters"],
  },
  roommates: [{roommate: {type: Schema.Types.ObjectId, ref: "User"}, status: {type: String, default: "pending"}, requests: [{description: String, amount: Number}], balance: Number}]
})

What gives? I've gotten this populate method to work before in a different app, but it's not giving me the referenced objects back, just the normal object as it exists inside the array without it's essential user details.

Here's the response.. but that _id should populate into an objetx with other properties like a name etc...:

   [
  {
    "_id": "57f17d5f51cdcb0b5cefe74d",
    "balance": 0,
    "requests": [],
    "status": "pending"
  }
]

It's the roommate field within the roommates array that's the reference in your schema, so you need to use dot notation in your populate call:

User.findOne({
  _id: req.params.id
})
.populate("roommates.roommate")
.exec(function(err, user) { ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM