これについて多くの質問がありますが、間違っている箇所は見つかりません。 populateを使用して「外部キー」を取得するとき、フィールドは未定義です。mongooseは未定義のフィールドに値を設定します
ユーザーモデル:
var userSchema = new Schema({
email : { type: String, required: true, unique: true },
password : { type: String, required: true },
firstname : { type: String, required: true },
lastname : { type: String, required: true },
created_at : Date,
updated_at : Date,
office : [ { type: Schema.Types.ObjectId, ref: 'Office' } ]
});
var User = mongoose.model('User', userSchema, 'User');
module.exports = User;
オフィスモデル:
var officeSchema = new Schema({
name : { type: String, required: true },
address : String,
city : String,
geolocation : [ { type: Schema.Types.ObjectId, ref: 'Geolocation' } ],
company : [ { type: Schema.Types.ObjectId, ref: 'Company' } ]
});
var Office = mongoose.model('Office', officeSchema, 'Office');
module.exports = Office;
移入コード:
User.find({})
.populate('office')
//.populate('office', 'name') I tried this too
.exec(function (err, users) {
if (err) return handleError(err);
users.forEach(function(user){
console.log('Office name: ', user.office.name);
});
});
私はユーザーのオフィス名を取得したいと思います。しかし、このuser.office.name
は私を返してくれません。私がこれをしたらuser.office
私は名前フィールドでオブジェクトを見ることができます。しかし、私は名前フィールドへのアクセス権を持っていません。
'user.office'フィールドはスキーマ内の配列です。 'user.office [0] .name'などを試してください。 –
ニース、そうです!配列なしでデータを使用するようにモデルを変更することはできますか?それが動作します ? – John
'['& ']'を削除することで、スキーマレベルで簡単に変更できます。 –