我正在尝试在我的 api 中集成创建用户的可能性。我正在使用 Node 和 mongodb。这是我的架构:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const FileSchema = new Schema({
name: {
type: String,
required: true,
minlength:1,
unique:false,
}, extension: {
type:String,
required:true,
unique:false,
}, content: {
type:String,
required:true,
unique:false,
},group:{
type:String,
required:false,
unique:false,
}, creator:{
type: String,
required: true,
unique:false,
}
})
const File = mongoose.model('File', FileSchema);
module.exports = File;
这是我的功能:
const createNewFile = (req, res) => {
const name = req.body.name;
const extension = req.body.extension;
const creator = req.body.creator;
const group = req.body.group;
console.log(req.body)
const newFile = new File({name, extension, content:'Write your code here',creator, group:group});
newFile.save()
.then(() => res.json('200'))
.catch(err => res.status(400).json('ERROR:'+err))
}
Insomia 和 Postman 控制台返回标题中的错误。我该怎么做才能避免这个错误?我添加了 unique: false
因为我在另一个问题中读到了它,但它还是失败了。有人可以帮帮我吗?当数据库为空时,我可以创建第一个元素。然后,当我创建第二个时,错误出现。请帮助我
最佳答案
在 mongodb Node 中有一个唯一索引 {key: 1}
在 files
集合myFirstDatabase
数据库。
我怀疑这是在您测试潜在架构设计时创建的。
为了插入不包含该字段唯一值的文档(包括不包含该字段),需要删除该索引。
实现这一目标的几种方法:
- 使用 mongo shell 或 Compass 或 Robo3t 等管理工具连接到 mongod,并手动删除索引
- 使用
syncIndexes
由 Mongoose 提供 - 删除
files
收藏 - 删除
myFirstDatabase
数据库 - 停止 mongod,删除整个 dbpath,然后使用干净的实例重新开始
关于node.js - "ERROR:MongoServerError: E11000 duplicate key error collection: myFirstDatabase.files index: key_1 dup key: { key: null }",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70187780/