【问题标题】:Mongoose Populate not working with Array of ObjectIdsMongoose Populate 不适用于 ObjectIds 数组
【发布时间】:2017-02-22 02:07:45
【问题描述】:

这是我的架构:

/** Schemas */
var profile = Schema({
    EmailAddress: String,
    FirstName: String,
    LastName: String,
    BusinessName: String
});

var convSchema = Schema({
    name: String,
    users: [{
        type: Schema.Types.ObjectId,
        ref: 'Profiles'
    }],
    conversationType: {
        type: String,
        enum: ['single', 'group'],
        default: 'single'
    },
    created: {
        type: Date,
        default: Date.now
    },
    lastUpdated: {
        type: Date,
        default: Date.now
    }
});

/** Models */
db.Profiles = mongoose.model('Profiles', profile);
db.Conversations = mongoose.model('ChatConversations', convSchema);

module.exports = db;

然后我尝试使用以下代码 (http://mongoosejs.com/docs/populate.html) 填充用户:

db.Conversations.find(query).populate('users').exec(function (err, records)     {
    console.log(records);
});

这将返回 recordsusers 数组作为空白数组 []

我也尝试了相反的方法(http://mongoosejs.com/docs/api.html#model_Model.populate):

db.Conversations.find(query, function (err, records) {
    db.Conversations.populate(records, {path: "users", select: "BusinessName"}, function (err, records) {
        console.log(records);
    });
});

结果是一样的。当我将参考资料检入个人资料收集记录时。

知道这里有什么问题吗?

【问题讨论】:

  • 似乎一切正常。它为我工作。看不出有什么问题
  • 哪一个有效?

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


【解决方案1】:

我通过重命名模型(第 3 次争论)使其工作:

mongoose.model( "Profiles", profile, "Profiles" );

问题是 Mongoose 正在搜索 profiles 集合,但它在数据库中为 Profiles。所以我将它重命名为Profiles 以匹配确切的名称。

呸!谢谢我。

【讨论】:

    猜你喜欢
    • 2020-05-18
    • 2020-07-21
    • 2016-03-24
    • 1970-01-01
    • 2016-10-14
    • 2013-12-17
    • 2015-08-16
    • 1970-01-01
    相关资源
    最近更新 更多