0

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,
    },
2
  • can you share your house and user schema? Commented Feb 7, 2022 at 18:31
  • @sinabariaji edited accordingly Commented Feb 7, 2022 at 19:12

1 Answer 1

1

use populate

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

Sign up to request clarification or add additional context in comments.

2 Comments

This returns an empty array for some reason. I even changed it to populate({path: 'users', model: 'User'}); but it still gives an empty array
check this

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.