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');
}
});
});