【问题标题】:check an existing data if not then create mongodb and monggose如果没有,请检查现有数据然后创建 mongodb 和 mongoose
【发布时间】:2021-06-26 04:19:00
【问题描述】:

我正在尝试对 MongoDB 数据进行预先存在检查,如果不存在则插入,但不知何故我无法执行该操作。当我在 express 上进行控制台日志时,它确实捕获了数据,但不知何故它不起作用。这是我的模型和其他 API:

const mongoose = require("mongoose");
const {ObjectID} = mongoose.Schema.Types;

const ScheduleSchema = mongoose.Schema({
    startdate: {type: Date},
    enddate: {type: Date},
    dateadded: {type: Date,default: Date.now},
    userid:[{type:ObjectID, ref:"User"}],
  },{ timestamps: true });
  
  module.exports = mongoose.model("Schedule", ScheduleSchema)

API:

const Schedule = require('../models/schedules')


router.post('/schedule/addschedule/:id',JWTAuthenticatToken, async (req, res) => {   
   const{startdate,enddate} = req.body

    //the console log did print out the data
    //{
    //startdate: '2021-04-05T06:27:40.000Z',
    //enddate: '2021-04-08T16:00:00.000Z'
    //}
    //6055e1ed5eec1e1c10df91d4

   console.log(req.body)
   console.log(req.params.id)

    const existingSchedule = await Schedule.find({startdate: startdate,enddate:enddate,userid:req.params.id})
    if(existingSchedule){
        return res.json({statusCode: "409", msg:'This schedule already exisits!'});
    }else{
        const schedule = new Schedule({
            startdate: startdate,
            enddate:enddate,
            userid:existingSchedule.req.params.id})            
            const scheduleresult = await schedule.save()
            return res.json({statusCode: "200"})
    }
});

我想知道我哪里出错了?非常感谢,非常感谢任何帮助。再次感谢。

【问题讨论】:

    标签: node.js database mongodb mongoose mongodb-query


    【解决方案1】:

    https://mongoosejs.com/docs/tutorials/findoneandupdate.html

    使用 upsert 选项,您可以使用 findOneAndUpdate() 作为查找和更新操作。如果 upsert 找到与过滤器匹配的文档,则它的行为类似于普通的 findOneAndUpdate()。但是,如果没有文档匹配过滤器,MongoDB 将通过过滤器和更新组合插入一个,如下所示。

    doc = await Schedule.findOneAndUpdate(filter, update, {
      new: true, // You should set the new option to true to return the document after update was applied.
      upsert: true // Make this update into an upsert
    });
    

    【讨论】:

      猜你喜欢
      • 2014-07-01
      • 2021-04-05
      • 1970-01-01
      • 2015-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-08
      • 2015-09-20
      相关资源
      最近更新 更多