2017-05-24 8 views
2

私はnodejs、mongodb/mongoose、expressでapiを作成して、jsonデータ、より具体的には2つのmongodbコレクション(1:datas 2:produits)でCRUD要求を作成しました。Mongoose APIリクエストとPostmanを使用して空の配列を返しますか?

"datas"コレクションは "User"スキーマにバインドされています。
"produits"コレクションは、 "製品"スキーマにバインドされています。

私の問題がある:「ユーザー」スキーマで
、私は/ produitsコレクションから、製品のIDを救うでしょう場所Productlistを持っています。

私のユーザー・スキーマは次のようになります。

//Get module 
var mongoose = require('mongoose'); 
var prodSch = require('../models/productSchema'); 
var Schema = mongoose.Schema; 

//Create user shema 
var user = new Schema({ 
"UIDUser": String, 
"IDUser": String, 
"UIDACL": String, 
"DatasUser": { 
    "acl_user_id": String, 
    "prenom": String, 
    "role": String, 
    "nom": String, 
    "pseudo": String, 
    "email": String 
}, 
    "Productlist" : [{ type: Schema.Types.ObjectId, ref: 'prodSch'}], 
    "Data_Unknown": {} 
}, 
{ 
    collection : 'datas' // define the collection to use 
}); 

//Export schema 
module.exports = mongoose.model('userSch', user); 

だから私のUserスキーマはdataschema.jsに保存されます。

私は別のファイルproductSchema.jsproductのスキーマを持っています。

//Get module 
var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 

//Create product shema 
var Product = new Schema({ 
    "product": String, 
    "UIDProduct": String, 
    "HashKey": String, 
    "EAN13": String, 
    "UIDReader": String, 
    "URL": String, 
    "readers_Label": String, 
    "devices_Label": String, 
    "EntryCatalis": [{ 
     "TETITISC": String, 
     "TEGRDIMG": String, 
     "TEPETIMG": String, 
     "TEREFIMG": String, 
     "LISCEISC": String 
    }], 

    "URLHeader": { "Content-Length": Number, "Last-Modified": String}, 
    "ExpireOn": String, 
    "Data_Unknown": {} 
}, 
{ 
    collection : 'produits' // Define the collection to use 
}); 

// exports schema 
module.exports = mongoose.model('prodSch', Product); 

私は、ユーザーProductlistで作成されたすべての製品のIDを保存する必要がある、と私はそれを行うために移入を使用する必要があります。

例:

product{name: tomato, origin: spain, id: 001} 

user{fname: john, lname: doe, Productlist: 001} //id of the product, saved 
               //via populate 

私はUserスキーマと私のProductスキーマのCRUD機能を初期化/作成するには、2つの異なるファイルを持っています。

これらのファイルには、投稿、取得、削除、get_by_Idなどのすべての機能があります。 2つのファイルに分かれています。

Productlist私はスキーマを定義しました。種類とdataschema.jsproductスキーマの参照:私はProductlistを移入する.post機能にいくつかのテストを実行しようとしましたdataschema.jsためCRUD機能を管理routeUser.jsで次に

"Productlist" : [{ type: Schema.Types.ObjectId, ref: 'prodSch'}] 

例:

.post(function(req, res){ 
    var newData = new userSch(); 

    newData.UIDUser = req.body.UIDUser; 
    newData.IDUser = req.body.IDUser; 
    newData.UIDACL = req.body.UIDACL; 
    newData.DatasUser = req.body.DatasUser; 
    newData.acl_user_id = req.body.acl_user_id; 
    newData.prenom = req.body.prenom; 
    newData.role = req.body.role; 
    newData.nom = req.body.nom; 
    newData.pseudo = req.body.pseudo; 
    newData.email = req.body.email; 
    newData.Data_Unknown = req.body.Data_Unknown; 

    newData.save(function(err){   
      if (err) 
       res.status(400).send(err); 

      userSch.find().populate('Productlist').exec(function (err, story) { 
       if (err) return handleError(err); 
       console.log('%s', userSch.Productlist); 
       res.json({message: "data created successfully"}); 
      }); 
    }); 
}); 

私はproductSchema.jsのためにCRUD機能を管理ファイルrouteProduct.jsでもテストを試してみました。

これで、userスキーマのProductlistでプロダクトIDを取得できません。 私は人口に関する多くのチュートリアルを検索しましたが、私の問題の正しいものは見つかりませんでした。

私はこの考えを理解していますが、正しく使用する方法はわかりません。

私のエラーとは何ですか、私のProductlistに正しく入力する方法を理解するのを助けてください。

編集:

私は自分のコードにいくつかの変更を行った、私はエラーなしで私の要求を行うことができますが、私の移入はまだ動作しません。これは私が変更したラインである

:そのコードで

.post(function(req, res){ 

    var newData = new prodSch(); 

    newData.product   = req.body.product; 
    newData.UIDProduct  = req.body.UIDProduct; 
    newData.HashKey   = req.body.HashKey; 
    newData.EAN13    = req.body.EAN13; 
    newData.UIDReader   = req.body.UIDReader; 
    newData.URL    = req.body.URL; 
    newData.readers_Label  = req.body.readers_Label; 
    newData.devices_Label  = req.body.devices_Label; 
    newData.EntryCatalis  = req.body.EntryCatalis; 
    newData.TETITISC   = req.body.TETITISC; 
    newData.TEGRDIMG   = req.body.TEGRDIMG; 
    newData.TEPETIMG   = req.body.TEPETIMG; 
    newData.TEREFIMG   = req.body.TEREFIMG; 
    newData.LISCEISC   = req.body.LISCEISC; 
    newData.URLHeader   = req.body.URLHeader; 
    newData['Content-Length'] = req.body['Content-Length']; 
    newData['Last-Modified'] = req.body['Last-Modified']; 
    newData.ExpireOn   = req.body.ExpireOn; 
    newData.Data_Unknown = req.body.Data_Unknown; 

    newData.populate('userSch').save(function(err){ // <--- The line 

     if (err) 
       res.send(err); 

     res.json({message: "data created successfully"}); 
    }); 
}); 

を、私は、CRUDのユーザーまたは製品ができますが、それは私のユーザー・スキーマ内の私Productlistを移入しません。

+0

オンラインスペルチェッカーで質問ベースを編集できますか?私はこれが迷惑になる可能性があることを知っている、あなたはすでにこの質問を作成するいくつかの時間を過ごしている。しかし、読むのは難しいです。 –

+0

あなたはより具体的になることができますか?申し訳ありませんがあなたの質問を正確に理解していない私はすべてを変更するか?それとも質問のタイトルだけ? – amalrik

+0

@DragandDrop私の編集が正しいと思っています、何かが間違っているなら、もう一度教えてください、ありがとう。 – amalrik

答えて

0

.populate()は、クエリ中にのみ有効であり、保存/更新/作成中ではないことを理解する必要があります。だからあなたの第二の例は、有益な何もしていません。

newData.populate('userSch').save(...) 

ユーザーのProductlistエントリを移入するためには、まずprodSch文書を必要としています。

既存のユーザーがいて、製品を製品リストに追加するとします。あなたは最初の製品を作成し、それを保存:

let product = new prodSch(req.body); 

product.save(function(err, product) { ... 

その後、あなたは私たちは、たとえば、userIdという変数をすることによって識別されますされ、既存のユーザーの製品リストに追加します。

我々は最初のユーザーを見つける:

userSch.findById(userId, function(err, user) { ... 

その後、我々は彼らの製品リストに製品を追加します。

user.Productlist.push(product); 

その後、我々は、ユーザセーブ:組み合わせ

user.save(function(err, user) { ... 

はすべてを(簡潔さのために間違いや存在チェックはしませんが、必ずそれを追加してください!):

let product = new prodSch(req.body); 

product.save(function(err, product) { 
    userSch.findById(userId, function(err, user) { 
    user.Productlist.push(product); 
    user.save(function(err, user) { 
     ...done... 
    }); 
    }); 
}); 

代わりのfindById/push/save、あなたはおそらくもfindByIdAndUpdateを使用することができます。

product.save(function(err, product) { 
    userSch.findByIdAndUpdate(userId, { 
    $push : { Productlist : product._id } 
    }, { 
    new : true // return the updated document, if you want 
    }, function(err, user) { 
    ...done... 
    }); 
}); 

次に、ユーザーを照会し、彼らが持っている製品のリストを移入するために:

userSch.findById(userId).populate('Productlist').exec(function(err, user) { 
    ... 
}); 

それは価値があります読むとを完全に理解人口に関する文書:http://mongoosejs.com/docs/populate.html

+0

ご返信ありがとうございます。あなたの投稿にあなたの助けを借りて私のコードにあなたのexempleを追加しようと思います。私はあなたにupvoteしたいが、私はそれを行うためのレベルを持っていない+10あなたに感謝多くの私はthis.thankを試してください – amalrik

+0

@amalrik確かに、あなたが問題に実行する場合は私にpingすることができます:) – robertklep

+0

私はしたいあなたの助けをたくさんありがとう。ありがとうございました – amalrik

関連する問題