首页 > 解决方案 > 我想检查我是否已经存储了数据,如果没有,那么我想将它存储在我的 mongodb 数据库中

问题描述

这是我正在使用的代码,所以如果我找到一个具有相同 uuid 的文档,我不想保存它。



const mongoose = require('mongoose');
mongoose.connect("mongodb+srv://connection string", {useNewUrlParser: true});
var db = mongoose.connection;
const Meeting = mongoose.model('Meeting',
  {
    host_id: String,
    topic: String,
    type: Number,
    start_time: String,
    duration: Number,
    timezone: String,
    created_at: String,
    join_url: String,
    agenda: String,
  });
        //STEP 4
        //we can now use the access token to make API calls
        request.get('https://api.zoom.us/v2/users/'+email+'/meetings', function (error, response, body) {
          if (error) {
            console.log('Error in API ', error)
          } else {
            body = JSON.parse(body);
            //display response in console
            console.log('API call ', body);       
            //save in db
            for (const m of body.meetings) {
             // m=JSON.parse(m);
              if(db.meeting.countDocuments({'uuid': m.uuid}, { limit: 1 })==0{
                let meeting = new Meeting(m);
                meeting.save();
              }
            }

          }






但我得到的错误是:TypeError:无法读取未定义的属性'countDocuments'。

标签: node.jsmongodbexpress

解决方案


查找具有特定 uuid 的文档的非常基本的请求,如果它不存在,请保存它。

Meeting.findOne({'uuid': uuid}, (err, existingMeeting) => {
    if (err) { 
      /* handle the error
      return / send a response */
    }
    if (existingMeeting) {
      /* handle the existence of this uuid
      return / send a response */
    }
    Meeting.save((err) => {
      if (err) { 
      /* handle the error in saving
      return / send a response */
      }
      /* everything has saved
      return / send a response */
    });
});

推荐阅读