简体   繁体   中英

MongoDB and Cosmos DB key error collection


I'm trying to create my first MongoDB app with Express & Angular & Azure Cosmos DB.
Here is my js files:

hero.model.js
  const mongoose = require('mongoose'); const Schema = mongoose.Schema; const heroSchema = new Schema({ id: { type: Number, required: true, unique: true }, name: String }, { collection: 'Heroes' }) const Hero = mongoose.model('Hero', heroSchema); module.exports = Hero; 
mongo.js
   const express = require('express');
    const bodyParser = require('body-parser');
    const path = require('path');
    const routes = require('./routes');
    const root = './';
    const port = process.env.PORT || '3000';
    const app = express();
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(express.static(path.join(root, 'docs')));
    app.use('/api', routes);
    app.get('*', (req, res) => {
    res.sendFile('docs/index.html', {root});
    });
index.js
  const express = require('express'); const bodyParser = require('body-parser'); const path = require('path'); const routes = require('./routes'); const root = './'; const port = process.env.PORT || '3000'; const app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(express.static(path.join(root, 'docs'))); app.use('/api', routes); app.get('*', (req, res) => { res.sendFile('docs/index.html', {root}); }); 
route.js
  const express = require('express'); const router = express.Router(); const heroService = require('./hero.service'); router.get('/heroes', (req, res) => { heroService.getHeroes(req, res); }); router.post('/hero', (req, res) => { heroService.postHero(req, res); }); router.put('/hero/:id', (req, res) => { heroService.putHero(req, res); }); router.delete('/hero/:id', (req, res) => { heroService.deleteHero(req, res); }); module.exports = router; app.listen(port, () => console.log(`API running on localhost:${port}`)); 
hero.service.js
  const Hero = require('./hero.model'); require('./mongo').connect(); function getHeroes(req, res) { const docquery = Hero.find({}); docquery .exec() .then(heroes => { res.status(200).json(heroes); }) .catch(error => { res.status(500).send(error); return; }); } function postHero(req, res) { const originalHero = { id: req.body.id, name: req.body.name }; const hero = new Hero(originalHero); hero.save(error => { if (checkServerError(res, error)) return; res.status(201).json(hero); console.log('Hero created successfully!'); }); } function checkServerError(res, error) { if (error) { res.status(500).send(error); return error; } } function putHero(req, res) { const originalHero = { id: parseInt(req.params.id, 10), name: req.body.name }; Hero.findOne({ id: originalHero.id }, (error, hero) => { if (checkServerError(res, error)) return; if (!checkFound(res, hero)) return; hero.name = originalHero.name; hero.save(error => { if (checkServerError(res, error)) return; res.status(200).json(hero); console.log('Hero updated successfully!'); }); }); } function deleteHero(req, res) { const id = parseInt(req.params.id, 10); Hero.findOneAndRemove({ id: id }) .then(hero => { if (!checkFound(res, hero)) return; res.status(200).json(hero); console.log('Hero deleted successfully!'); }) .catch(error => { if (checkServerError(res, error)) return; }); } function checkFound(res, hero) { if (!hero) { res.status(404).send('Hero not found.'); return; } return hero; } module.exports = { getHeroes, postHero, putHero, deleteHero }; 

It only works when I POST a new hero for the first time and a second time gives me an error: E11000 duplicate key error collection: admin.Heroes Failed _id or unique key constraint.

Please help!!

Thanks.

I know it's been a while but I've encountered the same problem. The solution is avoid using the field name id, rename it to UID or something. Once you done that you have to remove the entire collection and restart.

If you are following the Microsoft CosmosDB Angular tutorial, you can clone the repo below and test it on your local.

https://github.com/Azure-Samples/angular-cosmosdb

If you are using a newer version of mongoose you have to upgrade the connection string below.

         //useMongoClient: true
         useNewUrlParser: true 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM