我尝试了一些不同的事情,我只是不能让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 );
} );
基本上问题是数组不会将用户信息填充到项目中。
我做错了什么?
答案 0 :(得分:3)
您填充的user
字段嵌套在transactions
数组字段的子文档中,因此您需要在populate
调用中包含其完整路径:
Items.findOne().populate( 'transactions.user' ).exec( function( err, arr ) {
console.log( arr );
} );