Home > Mobile >  My save data to MongoDB not functioning, is it because my searching is wrong?
My save data to MongoDB not functioning, is it because my searching is wrong?

Time:06-03

I'm trying to make a comparison function. If the value that I search is not exist, the new value will be save to the database. But all I get is 0 new data found. So the system decides to not save the data. Is my searching wrong?

This is my code:

    var count = 0;
for (var t = 1; t < 151; t  ) {

    var searching = JobsSchema.find({ jobName: name[t], company: company[t] })

    if (searching == null) {

        count = count   1;

        var newJobs = new JobsSchema({
            "jobName": name[t],
            "country": country[t],
            "company": company[t],
            "jobType": type[t],
            "salary": salary[t],
            "skills": skills[t],
            "jobDesc": desc[t],
            "jobReq": req[t],
            "jobResponsibility": resp[t],
            "industry": industry[t],

        })

        newJobs.save(function (err, result) {
            if (err) {
                console.log(err);
            }
        })
    }
}

console.log(count   " new data found.");

CodePudding user response:

You should await your find function.
Also, change it to findOne to return a single instance of the JobsSchema and await the save call as well.
Finally you will need to wrap the code into an async function:

const saveData = async () => {
  var count = 0;
  for (var t = 1; t < 151; t  ) {
    var searching = await JobsSchema.findOne({
      jobName: name[t],
      company: company[t],
    });

    if (!searching) {
      count = count   1;

      var newJobs = new JobsSchema({
        jobName: name[t],
        country: country[t],
        company: company[t],
        jobType: type[t],
        salary: salary[t],
        skills: skills[t],
        jobDesc: desc[t],
        jobReq: req[t],
        jobResponsibility: resp[t],
        industry: industry[t],
      });

      await newJobs.save();
    }
  }

  console.log(count   ' new data found.');
};

saveData();
  • Related