猫鼬 .populate() 不填充

Mongoose .populate() not populating

我尝试了几种不同的方法,但我就是无法让 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 );
} );

问题本质上是数组没有将用户信息填充到项目中。

我做错了什么?

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

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