Home > Enterprise >  How can I get Node.js to create a simple database in MongoDB using Mongoose?
How can I get Node.js to create a simple database in MongoDB using Mongoose?

Time:11-13

This is the code I've been using in Node.js

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/vegesDB', {
  useNewUrlParser: true
});

const vegeSchema = new mongoose.Schema({
  name: String,
  rating: Number,
  review: String
});

const Vege = mongoose.model("Vege", vegeSchema);

const vege = new Vege({
  name: "Potato",
  rating: 9,
  review: "Very versatile vegetable"
});

vege.save();
mongoose.connection.close();

And this is the error message I get in the console:

C:\Users\85569\Desktop\Neptune Pluto\FruitsProject\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:153
          const err = new MongooseError(message);
                      ^

MongooseError: Operation `veges.insertOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (C:\Users\85569\Desktop\Neptune Pluto\FruitsProject\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:153:23)
    at listOnTimeout (node:internal/timers:564:17)
    at process.processTimers (node:internal/timers:507:7)

Node.js v18.6.0

For the record, I'm using MongoDB version v5.0.9 I have no other problems with the version of MongoDB I have loaded on my laptop. It's when I try to use Mongoose that everything goes haywire. Any information about the latest super-duper updated way of using Mongoose for this purpose would be greatly appreciated.

I've tried using variations of the above code suggested by other programmers on other sites and, to date, I haven't found one of them that works.

CodePudding user response:

There's nothing wrong is your code. Just add await before vege.save();.

Like this;

await vege.save();

CodePudding user response:

save() is a method on a Mongoose document. The save() method is asynchronous, so it returns a promise that you can await.

When you create an instance of a Mongoose model using new, calling save() makes Mongoose insert a new document.

In your case, you missed the await part so the mongoose failed to save the data.

to solve this issue use await vege.save()

(i.e)

const Vege = mongoose.model("Vege", vegeSchema);

const vege = new Vege({
  name: "Potato",
  rating: 9,
  review: "Very versatile vegetable"
});

await vege.save();

More about save() can be found here

  • Related