Home > Back-end >  How to return the object in an array object in mongoose
How to return the object in an array object in mongoose

Time:02-09

I currently have a UserModel and a House model where the house model contains an array of user objects. However, when I return I want to return an array of user objects instead of just users objectId. How do I accomplish this?

For example, if I run

HouseModel.findbyId("asdf") it returns:

_id: "asdf"
"name": "name",
    "users": [
        "620044aa7811fb4ab4619e44",
"620044aa7811fb4ab4619e45"
    ],

Any help would be appreciated

but I want to return:

``
_id: "asdf"
"name": "name",
    "users": [
        {_id: "620044aa7811fb4ab4619e44", name: "bob" age: 7,},
{_id: "620044aa7811fb4ab4619e45", name: "bob" age: 7,}
    ],
``

HouseSchema

const houseSchema = new mongoose.Schema({
    name: {
        type: String,
        required: false
    },
    users: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User",
            default: [],
            required: true,
        }
    ],

UserSchema

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        unique: true,
    },
    age: {
        type: Number,
        required: false,
        unique: true,
    },

CodePudding user response:

use populate

HouseModel.findbyId("asdf").populate('users')

  •  Tags:  
  • Related