Mongoose .populate()没有填充

时间:2015-11-13 00:08:08

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

我尝试了一些不同的事情,我只是不能让Mongoose将Users信息填充到Items集合中。

文件: users.js

var mongoose = require( 'mongoose' )
    Schema = mongoose.Schema,
    ObjectId = Schema.Types.ObjectId;

var userSchema = Schema( {
    _id: ObjectId,
    barcode: String,
    name: String,
    email: String,
    type: String
} );

var Users = mongoose.model( 'Users', userSchema );

module.exports = Users;
module.exports.schema = userSchema;

文件: items.js

var mongoose = require( 'mongoose' )
    Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId,
    Users = require( __dirname + '/users' ),
    userSchema = Users.schema;

var itemSchema = Schema( {
    _id: ObjectId,
    name: String,
    barcode: String,
    transactions: [ {
        date: Date,
        user: { type: ObjectId, ref: 'Users' },
        status: String
    } ]
} );

var Items = mongoose.model( 'Items', itemSchema );

module.exports = Items;
module.exports.schema = itemSchema;

这是我的测试代码:

var mongoose = require( 'mongoose' );
mongoose.connect( 'mongodb://localhost/booker' );

var Users = require( __dirname + '/models/users' );
var Items = require( __dirname + '/models/items' );

Items.findOne().populate( 'user' ).exec( function( err, arr ) {
    console.log( arr );
} );

基本上问题是数组不会将用户信息填充到项目中。

我做错了什么?

1 个答案:

答案 0 :(得分:3)

您填充的user字段嵌套在transactions数组字段的子文档中,因此您需要在populate调用中包含其完整路径:

Items.findOne().populate( 'transactions.user' ).exec( function( err, arr ) {
    console.log( arr );
} );