I am developing a NodeJS application with Express and MongoDB. My objects were not getting saved to the database, so I dug deeper and I found that the target collection was not created if I used:
const PersonSchema = new Schema({
firstName: String,
});
and the collection was created if I used
const PersonSchema = new Schema({
firstName: { type: String, unique: true},
});
In either case, the full model in server/models/person.js
is:
'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Use native promises.
mongoose.Promise = global.Promise;
// Define the Person schema.
const PersonSchema = new Schema({
// ...
});
const Person = mongoose.model('Person', PersonSchema);
module.exports = Person;
I have MongoDB 4.2.3 (with db.version()
in the mongo shell), npm 6.14.4, mongoose 5.7.5, and npm mongodb 3.3.2 (with npm list | grep mongodb
).
Why does MongoDB require a unique field in addition to _id
to create a collection?