Check if it exists before saving in moongodb and nodejs

1

I need to store an array in my MondoDB database. This I do without problems with the following code:

My array of objects:

[ { name: '1', type: 'float', value: 89.05, timestamp: 1535440000 },
  { name: '10', type: 'float', value: 19.67, timestamp: 1535440000 },
  { name: '15', type: 'float', value: 1.7, timestamp: 1535440000 },
  { name: '17', type: 'float', value: 2.2, timestamp: 1535440000 } ]

Save code:

data_Greenhouse.collection.insert(data_inver, function (err, docs) {
      if (err){
        res.status(500).send({message: 'Error al guardar en la base de datos'})
      } else {
        console.log("Multiple documents inserted to Collection Data_Greenhouse");
        res.status(200).send({data_Greenhouse: docs})
  }
});

I need to check before saving the array if in my collection there is already a record for the name field and for the date. If there is not save it and control it save it.

How could I do this?

Greetings, thank you. I hope that this well explained is something messy.

  

EDIT01

I publish the Post with a summary of what I need.

I really need to pass the object array to my query and check if it exists and generate a new one with the values that are not in the check in the database.

  

EDIT02

The code I am using is the following:

data_inver.forEach(elem => {
   var Yaexiste = Data_Greenhouse.findOne({ 'name': elem.name,'timestamp':elem.timestamp}); // Realizas la busqueda en la DB para cada objeto sino existe, entonces lo inserta
   console.log('mostramos los valores: ' + elem.name +" " +  elem.timestamp);

   console.log('mostramos los valores: ' + Yaexiste[0]);

   if(Yaexiste==undefined){
     data_Greenhouse.collection.insert(elem, function (err, docs) {
     if (err){
      res.status(500).send({message: 'Error al guardar en la base de datos'})
      console.log("Error");

     } else {
      console.log("Guardado");
      //res.status(200).send({docs})
     }
    });
  }else {
    console.log('Los datos ya existen');
  }
  });

The answer I get is the following:

mostramos los valores: 653 1535440000
mostramos los valores: undefined
Los datos ya existen
mostramos los valores: 657 1518420000
mostramos los valores: undefined
Los datos ya existen
mostramos los valores: 8 1535440000
mostramos los valores: undefined
Los datos ya existen

As you see it does not enter the if Yaexiste==undefined

Final solution:

If it behaves correctly I'll add it as an answer.

Data_Greenhouse.findOne({ 'name': elem.name ,'timestamp':elem.timestamp}, function (err, user) {
   console.log('mostramos los valores: ' + user);
   if(user==null){
     data_Greenhouse.collection.insert(elem, function (err, docs) {
     if (err){
      res.status(500).send({message: 'Error al guardar en la base de datos'})
      console.log("Error");

     } else {
      console.log("Guardado");
      //res.status(200).send({docs})
     }
    });
   }else {
    console.log('Los datos ya existen');
   }
   });
 });
    
asked by Manolait 05.09.2018 в 13:12
source

2 answers

1

You have an arrangement with objects to insert:

var PorInsertar=[
 { name: '1', type: 'float', value: 89.05, timestamp:1535440000 },
 { name: '10', type: 'float', value: 19.67, timestamp: 1535440000 },
 { name: '15', type: 'float', value: 1.7, timestamp: 1535440000 },
 { name: '17', type: 'float', value: 2.2, timestamp: 1535440000 } ];

You can see that arrangement

 PorInsertar.forEach(elem => {
 var Yaexiste=data_Greenhouse.findOne({ 'name': elem.name,'timestamp':elem.timestamp}); // Realizas la busqueda en la DB para cada objeto sino existe, entonces lo inserta
 if(Yaexiste==undefined){ 
   data_Greenhouse.collection.insert(elem, function (err, docs) {
   if (err){
    res.status(500).send({message: 'Error al guardar en la base de datos'})
   } else {
    console.log("Guardado");
   }
  });
 }
});
    
answered by 05.09.2018 / 16:30
source
1

Well indeed you have to create a previous query to see if it exists or not:

data_Greenhouse.findOne({ 'collection.name': '10' }, 'type value', function (err, data) {
  if (err) return handleError(err);
  aquí llamarias a la función que contiene el insert
});

There you have the code to search with a callback, as you will see the output parameters err and data , you have to evaluate data since it will tell you if the data exists or not what are you looking for?

I am writing another answer where you complement your doubt in a comment to a previous answer:

data_Greenhouse.find({}, 'name, type value', function (err, data) {
  if (err) return handleError(err);

  //Aquí puedes recorrer cada registro
  data.forEach(function(dato) {
      console.log(dato)
  });
});

You should evaluate data to see which index of that array shows or contains the records and then do the forEach

You can also be more specific in the query you can do this:

data_Greenhouse.collection.find({}, 'name, type value', function (err, data) {
  if (err) return handleError(err);

  data.forEach(function(dato) {
      console.log(dato)
  });
});

If the table is very large as you say, for those you use the filter within the find example:

If you look for a record in the table where you have name 10, you use this:

data_Greenhouse.find({'collection.name': '10'}, 'name, type value', function (err, data) { if (err) return handleError(err);

  //Aquí puedes recorrer cada registro
  data.forEach(function(dato) {
      console.log(dato)
  });
});

With the filter check if there is a record equal to the one you are going to insert

    
answered by 05.09.2018 в 13:47