简体   繁体   中英

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:

控制台输出显示创建的空文档

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!

Try change this:

const tourSchema = new mongoose.Schema();
({

to:

const tourSchema = new mongoose.Schema({

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));

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