【问题标题】:How to save each item in an array as a document using mongoose ? If any document matches item in array, it should not be created如何使用 mongoose 将数组中的每个项目保存为文档?如果任何文档与数组中的项目匹配,则不应创建它
【发布时间】:2020-03-10 17:50:48
【问题描述】:

我在猫鼬中有一个 categorySchema,如下所示:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const categorySchema = new Schema({
    name:{
        type: String,
        required:true
    }
},{timestamps:true});

module.exports = mongoose.model('Category',categorySchema);

我会像这样从请求中得到一个数组:

const categories = ['phones','computer','bikes','cars'];

我的类别收藏中已经有自行车和汽车。我可以遍历数组中的每个项目并将其保存为文档。但我需要每个文件都是独一无二的。没有两个同名的文件(显然)。我想我可以在查找查询中使用$in 找到现有文档,并通过遍历我获得的文档数组来删除每个文档,然后我可以遍历从请求中获得的数组并将每个项目保存为新文档。但我想知道是否有更好的方法。

【问题讨论】:

  • 按照 Janardan 的建议(推荐)通过设置 unique:true 来使用唯一索引。出于任何原因,您不能这样做,您始终可以查询文档以获取不同的值db.category.distinct( "name" ),这将根据您的需要为您提供结果,没有重复的名称。
  • 感谢您的想法。我会试试的。

标签: arrays node.js mongodb mongoose nosql


【解决方案1】:

你可以这样写你的架构:

const categorySchema = new Schema({
    name:{
        type: String,
        required:true,
        unique: true
    }
},{timestamps:true});

【讨论】:

  • 是的,转换了它!
猜你喜欢
  • 1970-01-01
  • 2019-04-16
  • 2019-06-29
  • 1970-01-01
  • 2012-01-19
  • 2016-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多