質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
MongoDB

MongoDBはオープンソースのドキュメント指向データベースの1つです。高性能で、多くのリトルエンディアンシステムを利用することができます。

Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

Q&A

解決済

2回答

3883閲覧

MongoDBからデータを取得する際、Mongooseのpopulate()が想定通りに動作しない

Shimane-man

総合スコア6

MongoDB

MongoDBはオープンソースのドキュメント指向データベースの1つです。高性能で、多くのリトルエンディアンシステムを利用することができます。

Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

0グッド

0クリップ

投稿2019/09/28 16:39

編集2019/09/29 08:39

前提・実現したいこと

MongoDBに、productsusersという2つのドキュメント情報を登録しています。
(下記に示します)
productsにuserIdというキーが存在し、Mongooseのpopulate()でproductsusersの情報を一度に取得できるようにしたいです。

![イメージ説明]

イメージ説明

ターミナル出力結果

該当のソースコードでの出力結果です。
私が期待している結果は、(8行目)userId: <ここにuser情報が出力> でした。
さらに次に示す該当コードの実行結果では、下記の通りuserIdが出力されてしまいます。

product

1[ 2 { 3 _id: 5d8f1e68ef4d75a940434aa6, 4 title: 'test', 5 price: 222, 6 description: 'test', 7 imageUrl: 'https://timedotcom.files.wordpress.com/2015/06/521811839-copy.jpg', 8 userId: 5d8f1a937c6be9a89d6491fc, 9 __v: 0 10 } 11]

該当のソースコード

Contorollerの記述:

js

1exports.getProducts = (req, res, next) => { 2 Product.find() 3 .populate('userId') 4 .then(products => { 5 console.log(products); 6 }); 7 }) 8 .catch(err => console.log(err)); 9};

Model(product)の記述:

js

1const mongoose = require('mongoose'); 2const Schema = mongoose.Schema; 3const productSchema = new Schema({ 4 title: { 5 type: String, 6 required: true 7 }, 8 price: { 9 type: Number, 10 required: true 11 }, 12 description: { 13 type: String, 14 required: true 15 }, 16 imageUrl: { 17 type: String, 18 required: true 19 }, 20 userId: { 21 type: Schema.Types.ObjectId, 22 ref: 'User', 23 required: true 24 } 25}); 26module.exports = mongoose.model('Product', productSchema); 27

Model(user)の記述:

js

1const mongoose = require('mongoose'); 2const Schema = mongoose.Schema; 3const userSchema = new Schema({ 4 name: { 5 type: String, 6 required: true 7 }, 8 email: { 9 type: String, 10 required: true 11 }, 12 cart: { 13 items: [ 14 { 15 productId: { 16 type: Schema.Types.ObjectId, 17 ref: 'Product', 18 required: true 19 }, 20 quantity: { type: Number, required: true } 21 } 22 ] 23 } 24}); 25 26module.exports = mongoose.model('User', userSchema);

試したこと

下記ドキュメントを参照しましたが、何が間違っているのか理解できませんでした。
https://mongoosejs.com/docs/populate.html

補足情報(FW/ツールのバージョンなど)

"mongoose": "^5.7.1",

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Shimane-man

2019/09/28 17:20

ご指摘ありがとうございます。修正しました。
guest

回答2

0

userの方に

JavaScript

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

が抜けているようですが、大丈夫でしょうか。

mongoose.modelとしての定義がないと、populateできないはずなので。

投稿2019/09/29 06:09

kabao

総合スコア648

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Shimane-man

2019/09/29 08:50 編集

ご回答ありがとうございます。 ご指摘の箇所は、貼り付ける際に漏れてしまっていました。 該当のコードは記述しております。質問のコードは修正しました。 お手を煩わせてしまい、申し訳ございません。
kabao

2019/09/29 09:19

うーんあとはなんでしょうね。 こちらのコードで、うまくpopulateされました。 https://github.com/satokano/nodemongoosesample > db.users.find() { "_id" : ObjectId("5d903e5d45fab034caf2c520"), "name" : "Alice", "email" : "alice@test.com" } > db.products.find() { "_id" : ObjectId("5d903ec545fab034caf2c521"), "title" : "test", "price" : 222, "description" : "test", "imageUrl" : "http://127.0.0.1:3000/", "userId" : ObjectId("5d903e5d45fab034caf2c520") } [ { _id: 5d903ec545fab034caf2c521, title: 'test', price: 222, description: 'test', imageUrl: 'http://127.0.0.1:3000/', userId: { cart: [Object], _id: 5d903e5d45fab034caf2c520, name: 'Alice', email: 'alice@test.com' } } ]
Shimane-man

2019/09/29 09:24

kabao様 ご指摘いただき、冷静になって一から確認していったところ、ルートの記述が間違っていたことに気づきました。ご丁寧に回答をいただき非常に嬉しく思います。ありがとうございます。
Shimane-man

2019/09/29 09:45

上記コード、実行して動作を自分でも確認しました。 色々、参考になりました。ありがとうございます。
guest

0

自己解決

原因は、本質門内に記載していない、ルートの記述が間違っていることでした。
つまり、質問内のコードの記述は想定内の動作をしますが、私が挙動を確認する方法に誤りがあったようです。
下記にコンソールの出力結果を示します。

shell

1[ 2 { 3 _id: 5d8f1e68ef4d75a940434aa6, 4 title: 'test', 5 price: 222, 6 description: 'test', 7 imageUrl: 'https://timedotcom.files.wordpress.com/2015/06/521811839-copy.jpg', 8 userId: { 9 cart: [Object], 10 _id: 5d8f1a937c6be9a89d6491fc, 11 name: 'Alice', 12 email: 'alice@test.com', 13 __v: 0 14 }, 15 __v: 0 16 } 17]

本質問にご回答、ご指摘をいただいた方にお礼申し上げます。

投稿2019/09/29 09:20

Shimane-man

総合スコア6

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問