gpt4 book ai didi

javascript - Mongoose .populate() 不填充

转载 作者:行者123 更新时间:2023-11-30 12:11:28 28 4
gpt4 key购买 nike

我尝试了几种不同的方法,但我就是无法让 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 数组字段的子文档中,因此您需要在 中包含其完整路径填充调用:

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

关于javascript - Mongoose .populate() 不填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33683776/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com