【问题标题】:saving documents to mongoDB preventing duplicates将文档保存到 mongoDB 以防止重复
【发布时间】:2021-01-07 17:08:05
【问题描述】:

我正在尝试使用 mongoose 在 mongodb 中保存多个文档;而且我也愿意防止重复。我的函数看起来像这样:

const Stock = require('./models/stock')
let _symbol = 'symb'

const writeToDB = async (dataObj) => {
    try {

        let stock = await Stock.find({symbol : _symbol } , function (err) {
            if(err) return null
        })

    if (!stock) {
        stock = new Stock({
            dataObj
        })
        await stock.save()
        console.log(`${symbol} is successfully saved to database`)
    } else {
        stock = await Stock.updateMany(
            dataObj, function (err) {
            if (err) {
                console.log(err)
            } else {
                console.log(`${symbol} successfully added`)
            }
        })
    }
    } catch (error) {
        console.log(error)
    }
    
}

但我不断收到超时错误。有人可以告诉我出了什么问题。

更新

使用处理良好的连接方法findOneAndUpdate()工作正常

【问题讨论】:

    标签: javascript node.js mongodb mongoose-schema


    【解决方案1】:

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

    var query = {symbol : _symbol };
    
    try{
       let result = await Stock.findOneAndUpdate(query, dataObj, {upsert: true})
    }
    catch(err){
      console.log();
    }
    
    

    如果你有一个大集合,为了提高速度findOneAndUpdate(),你应该索引symbol字段。

    当你使用asyncawait时,最好不要使用回调,使用trycatch

    【讨论】:

    • 感谢您的回答,但我不明白这个论点:“req.newData”?我认为您的代码中有一个小错误:“vanewData= dataObj”=>“var newData = dataObj”
    • 我在使用 findOneAndUpdate() 时不断收到此错误:Operation `stocks._findAndModify()` buffering timed out after 10000ms 是否有可能是由于 mongodb 连接错误而发生的?
    • 连接时是否使用此选项?特别是使用UnifiedTopology :true mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true }).then(...)
    【解决方案2】:

    我认为防止重复值的最佳、简单和简单的方法是在架构中使用 unique 值。

    因此,您的 Stock 架构必须具有与此类似的内容:

    symbol:{
      type: String, // or whatever
      unique: true
    }
    

    如果您尝试插入两个具有相同值的对象,mongoose 会出现如下错误:

    MongoError: E11000 duplicate key error dup key: { : "repeatedSymbol" }
    

    您也可以查看documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-25
      • 2018-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多