首页 > 解决方案 > 如何在 MongoDB 中保存相同的文档?

问题描述

我的架构

const mongoose = require('mongoose');


const test_schema = new mongoose.Schema({   
    Name: {
        type: String
    }
});

const chatting = mongoose.model('chat', test_schema);
module.exports = chatting;

获取上述模型给出架构

const chat = require('./models/chatting.js');

保存变量

const one = new chat({
    Name : "John"
})

const two = new chat({
    Name : "John"
})

现在保存

 await chat.insertMany([one, two])

但我得到重复的名称键错误

标签: node.jsmongodbmongoose

解决方案


您向我们提供了错误的架构。(test_schema != chatting_schema)。检查您的聊天模式,看看它的结构是否有点像这样:

const chatting_schema = new mongoose.Schema({   
    Name: {
        type: String
        unique: true
    }
});

如果是这样,请删除唯一属性。

此外,当您已经创建了一个文档时,您可以使用 .save() 函数,例如

await one.save(); 

推荐阅读