Wednesday 24 May 2017

how to use populate in a node api to save Json data from a collection to another schema collection

hi everyone first of all i want to apologise if my english aren't correct. i have created an api with nodejs mongodb/mongoose and express. my api work with all the crud options but that not the probleme.

i create this api tu make crud request to interact with json data, more specificaly with two mongodb collections (1: datas 2: produits).

the datas collections save json data from a User schema (with name age etc..), the produits collections save json data from a product schema(with origin-code, id-code etc...).

my problem is:

in User schema, i have a place "Productlist" who whill get/ save the ID of an element or many element of produits collections. my User shcema look like this:

//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' // defined the collection to use
 });

 // exports schema

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

so this is my "dataschema.js" wo defined the User schema. i have on a different file productSchema.js who defined the product schema.

//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' // defined the collection to use
});

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

so now, with my api with postman i can create a user or many user and product or many product. so i have those ellement on my db with ID etc... thats cool but for some reason i need to get all the product id or atleast one product id from the produits collection to save them in User "Productlist",

ex:

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

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

yo need to know that i also have two different "routes" files to create/initialise the crud option. one file for the User and one for the product.

in those files i have all the function for post, get, delete, get by id, etc... but separated in two files to have a clean workplace and difindes precisely each function for each schema.

so to populate:

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

in dataschema.js

then in the route files "routeUser.js" who manage the crud function for dataschema.js i tried to do some code in the post function to populate "Productlist"

ex:

.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"});
        });
    });
});

i tried to do userSch.find().populate('Productlist').exec .... also with the get function and the same in the file routeProduct.js who manage the crud function for the productSchema.js

so with this i cant get nothing in Productlist in my user schema. i have searched many tutorial for populate but each time the tutorial where to extreme for me to understand or where to different to be used with my project

i understand the idea but i don't know how to use it correctly can you please help me to past that problem and help me to understand what is my error and how to populate my "Productlist"? i'am present for any question about my code or my files or anything that can help you to understand my project, i'am sorry if my english is monstruous please excuse me thank you for your help good day to you.



via amalrik

No comments:

Post a Comment