如何使用猫鼬将数组中的每个项目另存为文档?如果任何文档与数组中的项目匹配,则不应创建该文档

我的猫鼬有一个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查找现有文档,并通过迭代获取的文档数组来删除每个文档,然后可以迭代从请求获取的数组并将每个项目另存为新的文件。但是我想知道是否有更好的方法。

red2yuri 回答:如何使用猫鼬将数组中的每个项目另存为文档?如果任何文档与数组中的项目匹配,则不应创建该文档

您可以这样编写模式: const categorySchema = new Schema({ name:{ type: String,required:true,unique: true } },{timestamps:true});

本文链接:https://www.f2er.com/3100560.html

大家都在问