Mongoose在Node JS中填充

Jes*_*ter 3 schema populate mongoose

我一直在努力关注Mongoose Population中的信息,但我得到了例外:

MissingSchemaError:尚未为模型"undefined"注册Schema.

我的代码是这样的:

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;});
    ...
}
Run Code Online (Sandbox Code Playgroud)

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

干杯.

Jon*_*ora 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);
});
Run Code Online (Sandbox Code Playgroud)

希望这能给你一些帮助.