Search code examples
node.jsmongodbexpressmongoosecompass

NodeJS MongoDB question save() function creating empty documents in collection


New to MongoDB and know some basic Node. Following an online tutorial for Node, Express and MongoDB. I have some code that is connecting to a remote cluster and pushing in a document into a collection. The connection works, but the document inserted is empty, as in, it contains just the autogenerated id. Here's the code:

const DB = process.env.DATABASE.replace(
  '<PASSWORD>',
  process.env.DATABASE_PASSWORD
);
mongoose
  .connect(DB, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
  })
  .then(() => console.log('DB Connection successful'));
 
const tourSchema = new mongoose.Schema();
({
  name: {
    type: String,
    required: [true, 'A tour must have a name'],
    unique: true,
  },
  rating: {
    type: Number,
    default: 4.5,
  },
  price: {
    type: Number,
    required: [true, 'A tour must have a price'],
  },
});
 
const Tour = mongoose.model('Tour', tourSchema);
 
const testTour = new Tour({
  name: 'aaaa',
  rating: 3.0,
  price: 397,
});
 
testTour
  .save()
  .then((doc) => {
    console.log(doc);
  })
  .catch((err) => console.log('ERROR:', err));

Here is the output:

Console output showing an empty doc created

If I look in Compass, I can see the empty document created, so the connection works. Could there be some different querystring params for the actual connection string? Here are the current querystring params for the MongoDB connection string (these were default): retryWrites=true&w=majority

Any idea what I may be missing in the code?

Thanks!


Solution

  • At line 13 you are not defining your schema correctly and there are no entities defined in it because you are closing the Schema with ; before defining.

    const DB = process.env.DATABASE.replace(
      '<PASSWORD>',
      process.env.DATABASE_PASSWORD
    );
    mongoose
      .connect(DB, {
        useNewUrlParser: true,
        useCreateIndex: true,
        useFindAndModify: false,
      })
      .then(() => console.log('DB Connection successful'));
    
    const tourSchema = new mongoose.Schema()
      ({
        name: {
          type: String,
          required: [true, 'A tour must have a name'],
          unique: true,
        },
        rating: {
          type: Number,
          default: 4.5,
        },
        price: {
          type: Number,
          required: [true, 'A tour must have a price'],
        },
      });
    
    const Tour = mongoose.model('Tour', tourSchema);
    
    const testTour = new Tour({
      name: 'aaaa',
      rating: 3.0,
      price: 397,
    });
    
    testTour.save()
      .then((doc) => {
        console.log(doc);
      })
      .catch((err) => console.log('ERROR:', err));