2

Forgive me but I have been trying to solve the problem for several days, but I can not locate the problem.

I am downloading from mongoDB^14..(with mongoose) two arrays with complementary data. One contains the user data, the other the user survey records. Both arrays are related through the user's email:

/***************************************************************
 This is what I download from mongoDB with Nodejs 
****************************************************************

const user = require ('../models/user');
const test = require ('../models/test'); 

 let users = await user.find ({email:userEmail});
 let tests = await test.find ({email:testEmail});

Request:

let users: [                                    
{name:'pp', email:'pp@gmail.com},
 {name:'aa', email:'aa@gmail.com'}
];

let tests: [
{email:'pp@gmail.com', satisfaction:'5'}, 
{email:'aa@gmail.com', satisfaction:'2'}];


*****************************************************************************/

Now I try to relate both json arrays using:

      for (let i = 0; i < prof1.length; i++) {
            for (let z = 0; z < registro1.length; z++) {

                       if (users[i].email==tests[z].email){
                              users[i]['satisfation'] = test[z].satisfation;
                          }                 
                }
            }

If I do a console.log(users[0]) my wish is:

{name:'pp', email:'pp@gmail.com', satisfation:'5'}

But I receive:

{name:'pp', email:'pp@gmail.com'}

But attention¡¡¡¡ If I do a console.log(users[0].satisfation)

The result is: 5

?????? Please can someone help me. Thank you very much

Note: If I instead of downloading the mongodb arrays, I write them by hand. So it works perfectly. Can it be a lock on the models?

WIDE INFORMATION Although I have given a simple example, the user and test arrays are much more complex in my application, however they are modeled and correctly managed in mongoDB. The reason for having two documents in mongoDB is because there are more than 20 variables in each of them. In user, I save fixed user data and in the test the data that I collect over time. Later, I lower both arrays to my server where I perform statistical calculations and for this I need to generate a single array with data from both arrays. I just take the test data and add it to the user to relate all the parameters. I thought that in this way it would unburden the mongoDB to carry out continuous queries and subsequent registrations, since I perform the operations on the server, to finally update the arry test in mongoDB. When I query the database I receive the following array of documents:

let registroG = await datosProf.find({idAdmin:userAdmin });
res.json(registroG);

This is the response received in the front client:

enter image description here

If I open the object the document [0] would be:

enter image description here

**THE QUESTION **: Why when I try to include a value key in the object it doesn't include it?

Frank
  • 403
  • 3
  • 10
  • 1
    `users[i].['satisfation']` makes no sense to be honest. Could you provide a reproducible example? Current edition requires a lot of guess work. I believe it is related to how you deal with mongoose models. They are not POJOs and should be used according according to the docs. It's all my speculations tho. There is not enough information in the question to provide definitive answer. – Alex Blex Jun 24 '21 at 15:18
  • 1
    Ah, an one more comment about the loops themselves - it's O(n^2) complexity. I am pretty sure you can do it much more efficiently on mongo side if you explain what you are actually trying to achieve. – Alex Blex Jun 24 '21 at 15:22
  • Sorry, I made a point, I correct it(users[i]['satisfation'] ). – Frank Jun 24 '21 at 15:35
  • #Alex Blex Sorry I didn't answer you before, but your answer has made me reflect. Thanks for your contribution. I split my document in mongoDB in two for easier management and scalability. However, you are right and I have a single document again since they are one-to-one relationships. I really liked your way of making people reflect. Thank you. – Frank Jun 25 '21 at 08:09
  • However, the handling of json bothers me, since in another application that I have in production, the object.key = value model works perfectly. Obviously in the case of this question, I do not understand very well why it does not include the new variable in the json. Therefore, although I am going to change my development, I would like to deepen why it does not perform the function correctly. – Frank Jun 25 '21 at 08:14
  • 1
    You still can merge both collections on mongo side with $lookup aggregation. Mongo can benefit from indexes to inject subdocuments into main collection and use all of processor threads instead of 1 available to nodejs. You realise you are blocking the event loop with these nested cycles, don't you? – Alex Blex Jun 25 '21 at 09:06
  • 1
    Regarding THE QUESTION - it's a duplicate of https://stackoverflow.com/questions/18554350/unable-to-add-properties-to-js-object . Essentially you oversimplify nodejs data model. It appears as json but in fact it is bson on the wire, converted to nodejs object, than converted to Mongoose model - an object with half of the methods aimed to ensure that it contains only properties defined in the schema. – Alex Blex Jun 25 '21 at 09:16
  • Alex thank you very much again for your contribution. You are right, in both comments. I am going to study both, because I did not know that the event loop was blocking, at all times I thought it was working asynchronously. In case someone can also help you, I have attached a link where Nodejs explains the subject - https://nodejs.org/en/docs/guides/dont-block-the-event-loop/ - Thank you very much again. I will listen to you in both comments I study the locks and analyze the threads in mongoDB. I take my hat off to you! – Frank Jun 25 '21 at 09:59

1 Answers1

0

You could use Array.map with es6 spread operator to marge to objects

let users = [{ name: 'pp', email: 'pp@gmail.com' }, { name: 'aa', email: 'aa@gmail.com' }];
let tests = [{ email: 'pp@gmail.com', satisfaction: '5' }, { email: 'aa@gmail.com', satisfaction: '2' }];

let result = users.map(v => ({
  ...v,
  ...tests.find(e => e.email == v.email)
}))
console.log(result)
Nur
  • 2,361
  • 2
  • 16
  • 34
  • Thank you very much Nur, this work ok, but as I have commented if you write it manually it works. With your code, in the console I have this: – Frank Jun 24 '21 at 14:00
  • { '$__': InternalCache { strictMode: true, selected: {},shardval: undefined, saveError: undefined, validationError: undefined,saving: undefined, adhocPaths: undefined,removing: undefined, inserting: undefined, saving: undefined, version: undefined,getters: {}, _id: 60d3486f9f9dfd4c457c0e4c, populate: undefined, ............._doc: { name: 'pp’,email: 'pp@gmail.com', satisfation: 5,__v: 0 }, '$init': true }, – Frank Jun 24 '21 at 14:05