我结合使用Find方法和$or运算符来判断数据库,以查找第const duplicate = await NewItemsData.find({ $or: newItems });行中任何现有的重复数据.判断控制台console.log(duplicate)中的变量时,我发现一些获取的数据丢失了.以下是代码:

请帮我弄清楚这个问题是从哪里来的.代码的目的是创建一个包含重复数据的数组,然后过滤newItems数组,创建另一个包含已存在于newItems数组中但不存在于重复数组中的数据的array.

const createMoneyInTransact = asyncHandler(async (req, res) => {
 const {newItems}= req.body
 console.log(newItems)

//check the database to see if any data found in the newItems array coming in from the frontend
//already exists in the NewItemsData database if it exists, create a new array of all duplicates

  const duplicate = await NewItemsData.find({ $or: newItems });
  console.log(duplicate)
     if(Array.isArray(duplicate) && duplicate.length === 0){
        console.log('no duplicates')
         const create_newItems = await NewItemsData.create(newItems)
       console.log(create_newItems)
    }else{
        console.log('duplicate exists')
        //helper function that compares two objects in arrays by their properties
    const containsObject=(obj, arr, key)=>{
        return arr.some((element)=>{
            return element[key] === obj[key]
        })

     }

     // Filter the newItems array and keep only the objects that are 
     //not in the duplicate array
     const newUniqueItems = newItems.filter((obj)=>{
         return !containsObject(obj, duplicate, 'productName')
     })

     console.log(newUniqueItems)
     const create_newUniqueItems = await NewItemsData.create(newUniqueItems)
     console.log(create_newUniqueItems)

    }
})


//console.log Data
//console.log(newItems) displays the result below
[
  {
    productName: 'vally',
    sellingPriceOfTotal: 3619,
    quantityCount: 11,
    unitOfQuantity: 'grams',
    sellingPrice: '329'
  },
  {
    productName: 'Tridant',
    sellingPriceOfTotal: 2400,
    quantityCount: 4,
    unitOfQuantity: 'grams',
    sellingPrice: '600'
  },
  {
    productName: 'trulia',
    sellingPriceOfTotal: 1600,
    quantityCount: 4,
    unitOfQuantity: 'kg',
    sellingPrice: '400'
  },
  {
    productName: 'constr',
    sellingPriceOfTotal: 1362,
    quantityCount: 3,
    unitOfQuantity: 'kg',
    sellingPrice: '454'
  }
]
//console.log(duplicate) displays the result below
[
  {
    _id: new ObjectId("6598d46d37efd2db72ee9ecd"),
    productName: 'Tridant',
    sellingPriceOfTotal: '2400',
    quantityCount: 4,
    unitOfQuantity: 'grams',
    sellingPrice: 600,
    __v: 0
  },
  {
    _id: new ObjectId("6599150ebd9fedd3f0b9e721"),
    productName: 'trulia',
    sellingPriceOfTotal: '1600',
    quantityCount: 4,
    unitOfQuantity: 'kg',
    sellingPrice: 400,
    __v: 0
  }
]

//productName: vally was surposed to be among the duplicate but was not picked up
//console.log(newUniqueItems) displays the result below
[
  {
    productName: 'vally',
    sellingPriceOfTotal: '3619',
    quantityCount: 11,
    unitOfQuantity: 'grams',
    sellingPrice: 329
  },
  {
    productName: 'constr',
    sellingPriceOfTotal: '1362',
    quantityCount: 3,
    unitOfQuantity: 'kg',
    sellingPrice: 454
  }
]
//but vally is not supposed to be among the filtered array because it is a duplicate hence
//the errow message below

MongoServerError: E11000 duplicate key error collection: test.newitemsdatas index: productName_1 dup key: { productName: "vally" }
    at C:\Users\USER\Desktop\bussiness-books\server\node_modules\mongodb\lib\operations\insert.js:50:33
    at C:\Users\USER\Desktop\bussiness-books\server\node_modules\mongodb\lib\operations\command.js:84:64
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

//here is the NewItemsData Data Model
const mongoose = require('mongoose');
const MoneyInData = require('./MoneyInData');

const newItemsSchema = new mongoose.Schema({

    productName:{
        type: String,
        required: true,
        unique: true
    },
    sellingPriceOfTotal:{
      type: String,
      //required: true
    },
    quantityCount: {
        type: Number,
    },
    unitOfQuantity:{
        type: String,
    },
    costPrice:{
      type: Number,
      //required: true
    },
    sellingPrice:{
        type: Number,
       required:true
    },
    moneyInData:{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'MoneyInData'
    },

})

module.exports = mongoose.model('NewItemsData', newItemsSchema);

推荐答案

看起来您只需要在查询中判断productName个匹配项.在判断整个文档匹配的那一刻,我的意思是[ productName, sellingPriceOfTotal, quantityCount, unitOfQuantity, sellingPrice]个文档中的所有5个都需要完全匹配,对象才能匹配.我怀疑您集合中productName: 'vally'的文档与您用来搜索的文档有细微的不同.

取而代之的是,只需通过try 其中一个来寻找匹配的productName.

Option 1 using 100

const {newItems} = req.body;

// Create a new array of objects containing just the productName and it's value
const newItemsNamesObj = newItems.map(o =>{
  return {productName: o.productName}
})
//Then search using $or
const duplicate = await NewItemsData.find({ 
   $or: newItemsNamesObj 
});

Option 2 using 100

const {newItems} = req.body;

// Create a new array of String containing just the productName
const newItemsNamesStr = newItems.map(o =>{
  return o.productName
})
//Then search
const duplicate = await NewItemsData.find({
   productName: {
      $in: newItemsNamesStr
   }
});

Javascript相关问答推荐

在JavaScript中检索一些文本

为什么我达到了时间限制!?LeetCode链接列表循环(已解决,但需要解释!)

当在select中 Select 选项时,我必须禁用不匹配的 Select

Plotly热图:在矩形上zoom 后将zoom 区域居中

通过嵌套模型对象进行Mongoose搜索

如何强制Sphinx中的自定义js/css文件始终加载更改而不缓存?

将核心模块导入另一个组件模块时存在多个主题

当输入字段无效时,我的应用程序不会返回错误

未加载css colored颜色 ,无法将div设置为可见和不可见

NG/Express API路由处理程序停止工作

Rxjs流中生成IMMER不能在对象上操作

Reaction Redux&Quot;在派单错误中检测到状态Mutations

从另一个数组中的对应行/键值对更新数组中的键值对对象

钛中的onClick事件需要在两次点击之间等待几秒钟

在FAQ Accodion应用程序中使用React useState时出现问题

删除元素属性或样式属性的首选方法

如何在AG-Grid文本字段中创建占位符

我不知道如何纠正这一点.

如何使用[ModelJSON,ArrayBuffer]调用tf.loadGraphModelSync

当达到高度限制时,如何裁剪图像?使用html和css