2016-12-15 10 views
0

を未定義の参照を返すに移入します。マングースは、私はので、私はおそらくここで何かを見逃しているマングースすることはかなり新しいです

私は2つのコレクション "Company"を持っています& "User"会社に所属するすべてのユーザーを取得しようとしていますが、ユーザーのオブジェクトではなく会社のユーザー配列がundefinedを返しています。

私はドキュメントを読んで、正しい方向にステップしているように見えましたが、配列に保存する方法については何も言及していません。オブジェクトをユーザーオブジェクトのemailsプロパティに追加しますか?

は、私は非常にmysqlの重い背景から来て、私は多分誰かがMongoDBのは、関係をどのように処理するかを説明することができれば幸いです間違っ代をやって?

会社スキーマ

const companySchema = new Schema({ 
    name: String, 
    slug: String, 
    _creator: { type: Schema.Types.ObjectId, ref: 'User' }, 
    users: [{ type: Schema.Types.ObjectId, ref: 'User' }], 
    created_at: Date, 
    updated_at: Date 
}); 

module.exports = mongoose.model('Company', companySchema); 

ユーザー・スキーマ

const userSchema = new Schema({ 
    first_name: String, 
    last_name: String, 
    username: String, 
    password: String, 
    companies: [{ type: Schema.Types.ObjectId, ref: 'Company' }], 
    created_at: Date, 
    updated_at: Date 
}); 

module.exports = mongoose.model('User', userSchema); 

保存ユーザー

const dave = new User({ 
    first_name: 'Dave', 
    last_name: 'Hewitt', 
    username: 'moshie', 
    password: '123456789', 
    updated_at: new Date() 
}); 

dave.save() 
    .then(function (user) { 
     const indigoTree = new Company({ 
      name: 'IndigoTree', 
      slug: 'indigotree', 
      _creator: dave._id, 
      updated_at: new Date() 
     }); 

     indigoTree.users.push(user); 

     return indigoTree.save(); 
    }) 
    .then(function (company) { 
     console.log(company); 
    }) 
    .catch(function (error) { 
     console.log(error); 
    }); 

ユーザーをチェック

Company.find({}).populate('users').exec() 
    .then(function (doc) { 
     doc.users // undefined? 
    }); 

アイデア?

答えて

0

あなたはusers配列にuserを推進しています。その代わりに、あなたはすなわちuser._id配列にpushuser's Idする必要があります。

を置き換えますと

indigoTree.users.push(user); 

indigoTree.users.push(user._id); 

をまた、find()クエリはarray of documentsを返しますので、あなたはdoc[0].users、ないdoc.usersを使用する必要があります。

Company.find({}).populate('users').exec() 
    .then(function (doc) { 
     doc[0].users // undefined? -> change here, it wont come undefined 
    }); 

また、あなたはobject返しfindOne()の代わりfind()、使用することができます。その場合、あなたは使用することができますdoc.users

Company.findOne({_id: someCompanyId}).populate('users').exec() 
    .then(function (doc) { 
     doc.users // it wont come undefined 
    }); 
0

API Docsによると、Mongooseのfind()は、単一アイテムの代わりに配列コレクションを返します。 findOneについては

()それは(カウント、潜在的にヌル単一の文書で、()文書のリストを見つける。)等の文書の数、更新()影響を受けた文書の数、

Company.find({}).populate('users').exec().then((doc) => { 
    console.log(doc[0].users); // prints users array 
}); 
関連する問題