【问题标题】:array of object populate returns null mongoose对象填充数组返回 null mongoose
【发布时间】:2020-11-11 15:20:19
【问题描述】:

这返回 null 可能是什么问题?我在测试表中看到了正确的用户 _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');
}

【问题讨论】:

  • "...无论如何都解决了..." - 这是否意味着您已经找到了问题的解决方案?
  • 是的,我保留了这篇文章,以便其他人可以参考它,我使用的是 userModel 而不是 TestModel 小错字让我发帖
  • 好的。您可以将解决方案作为答案提交,以便将此问题标记为已回答。

标签: node.js mongodb mongoose mongoose-schema mongoose-populate


【解决方案1】:

无论如何都解决了

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

【讨论】:

    猜你喜欢
    • 2017-10-26
    • 2014-11-02
    • 2019-06-17
    • 2016-12-04
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    相关资源
    最近更新 更多