Search code examples
node.jsmongodbmongoosemongoose-schemamongoose-populate

array of object populate returns null mongoose


This returns null what could be the issue? I see proper user _id in the test table, I would expect user detail to be shown in the place user. As you can see under test array i made ref to user schema.

structure as follows in database

enter image description here

const mongoose = require('mongoose');

let UserSchema = new mongoose.Schema({
    email: String,
    password: String,
});

let testSchema = new mongoose.Schema({
    test: [
        {
            title: String,
            user: {
                type: mongoose.Schema.Types.ObjectId,
                ref: 'user',
            },
        },
    ],
});

run().catch((err) => console.log(err));

async function run() {
    await mongoose.connect('mongodb://localhost:27017/test', {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    });
    await mongoose.connection.dropDatabase();

    const UserModel = mongoose.model('user', UserSchema);
    const TestModel = mongoose.model('test', testSchema);

    const newUser = { email: 'test@test.com', password: 'Alexa123' };
    const user = new UserModel(newUser);
    await user.save();

    const newTest = { test: [{ title: 'foo', user: user._id }] };
    const test = new TestModel(newTest);
    await test.save();

    const getTest = await TestModel.findOne({ title: 'test' })
        .populate('test.user')
        .exec();
    console.log(getTest, 'returns null');
}


Solution

  • anyway solved by this

    const getTest = await TestModel.findOne({ _id: test._id })
            .populate('test.user')
            .exec();