猫鼬填充不与ObjectId数组一起使用 [英] Mongoose Populate not working with Array of ObjectIds

查看:100
本文介绍了猫鼬填充不与ObjectId数组一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的模式:

/** 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 ):

Then I try to populate Users using following code (http://mongoosejs.com/docs/populate.html):

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

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

This is returning records but users array as a blank array [].

我也尝试了另一种方法( http://mongoosejs.com/docs/api.html#model_Model.populate ):

I also tried the other way around (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);
    });
});

结果相同.当我检查对概要文件收集记录的引用时.

Results are same. When I checked references into profile collection records are there.

有什么想法吗?

推荐答案

我通过重命名模型(第三个观点)使它起作用:

I got it working by renaming model (the 3rd arguement):

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

问题是猫鼬在搜索profiles集合,但在数据库中以Profiles的形式出现.因此,我将其重命名为Profiles以匹配确切的名称.

The issue was Mongoose was searching for profiles collection but its there as Profiles in database. So I renamed it to Profiles to match the exact name.

Phewww!多亏我.

Phewww! Thanks to me.

这篇关于猫鼬填充不与ObjectId数组一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆