Mongoose在Node JS中填充

时间:2013-02-19 04:20:01

标签: schema mongoose populate

我一直在尝试关注Mongoose Population中的信息,但我得到例外:

MissingSchemaError:尚未为模型“未定义”注册架构。

我的代码是这样的:

mongoose = require('mongoose');
Schema = mongoose.Schema;
mongoose.connect(MONGO_SERVER);
ObjectId = Schema.ObjectId;

var FirstSchema = new Schema({
    label       : String
});
var SecondSchema = new Schema({
    first_id           : [{ type: mongoose.Schema.ObjectId, ref: 'First' }],
    type           : String,
    ...
});
var first= mongoose.model('First', FirstSchema);
var second= mongoose.model('Second', SecondSchema);

function test() {
    ...
    second.find({}).populate('first_id').exec(function(err,data){return true;});
    ...
}

错误发生在populate上,我已经多次调整它在论坛上找到的不同答案,我相信它会很简单,但是有人能指出我正确的方向吗?

干杯。

2 个答案:

答案 0 :(得分:7)

在模式定义中,我看到您已将“first_id”定义为第二个模式中的数组。与关系数据库相比,这将像一对多关系,其中父表是第二个集合,第一个集合作为子集。然后你试图用第一个填充第二个。

假设我有一个Users集合和一个Clients集合,其中每个客户端都有一个与之相关的用户。然后代码将是:

var mongoose = require('mongoose');
mongoose.connect('mongodb://userName:password@server:port/dbname');
var conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection error:'));
conn.once('open', function callback () {
    console.log('connected ');
});

var user = mongoose.Schema({
    userName: String
});

var client = mongoose.Schema({
    fk_user: { type: mongoose.Schema.ObjectId, ref: 'Users' },
    name: String
});

var UserModel = mongoose.model('Users', user);
var ClientModel = mongoose.model('Clients', client);

ClientModel.findOne().populate('fk_user').exec(function(err, c) {
    if (err) { return console.log(err); }

    console.log(c.fk_user.userName);
});

希望这能给你一些帮助。

答案 1 :(得分:0)

我有同样的错误

Schema尚未注册模型" States"。

有时也可能是您尝试引用的模型未分配给架构。

如下面的代码

首先:我试图引用'州'我使用States创建的模型,但它不是模型的名称,而是名称是状态

<header id="header" style="opacity: 1; top: 0px;">
            <div id="bara-wrap">
                    <img src="img/logo.png" alt="LOGO" class="logo" />
                    <nav id="bara">
                        <ul class="butoane">
                            <li><a href="#" class="home">home</a></li>
                            <li><a href="#" class="about">about</a></li>
                            <li><a href="#" class="skills">skills</a></li>
                            <li><a href="#" class="contact">contact</a></li>
                        </ul>
                    </nav>
                <ul class="social">
                    <li class="facebook">facebook</li>
                </ul>
            </div>
        </header>

同时模型的真实姓名是州

var CountriesSchema = new Schema({

name:{ type:String,required:true},
capital:{type:String},
description:{type:String},
cord:{

    latitude:{type:Number},
    longitude:{type:Number}

},
state:[{type:Schema.Types.ObjectId , ref:'States'}],
date_created:{type:Date},
date_modeified:{type:Date}



});

我所做的只是将州改为州

 var State = mongoose.model('states',StateSchema) ;

module.exports = State ;
相关问题