对象数组填充 returns 空猫鼬

array of object populate returns null mongoose

这个 returns null 可能是什么问题?我在测试 table 中看到正确的用户 _id,我希望用户详细信息显示在用户位置。正如您在测试数组下看到的那样,我引用了用户模式。

数据库中的结构如下

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');
}

无论如何都解决了

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