const mongoose = require("mongoose");
mongoose.connect("mongodb://127.0.0.1:27017/fruitsDB", { useNewUrlParser: true });
const fruitSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "Please check your data entry, no name specified!"]
},
rating: {
type: Number,
min: 1,
max: 6
},
review: String
});
const Fruit = mongoose.model("Fruit", fruitSchema);
const personSchema = new mongoose.Schema({
name: String,
age: Number
});
const Person = mongoose.model("Person", personSchema);
async function saveFruitAndPerson() {
try {
// Creating and saving a Fruit document
const fruit = new Fruit({
name: "Grapes",
rating: 6,
review: "Grape is a good fruit"
});
const savedFruit = await fruit.save();
console.log("Saved fruit:", savedFruit);
// Creating and saving a Person document
const person = new Person({
name: "John",
age: 37
});
const savedPerson = await person.save();
console.log("Saved person:", savedPerson);
// Using findOne to retrieve a Fruit document
const retrievedFruit = await Fruit.findOne({ name: "Grapes" });
console.log("Retrieved fruit:", retrievedFruit);
// Using findOne to retrieve a Person document
const retrievedPerson = await Person.findOne({ name: "John" });
console.log("Retrieved person:", retrievedPerson);
} catch (error) {
console.error("Error:", error);
} finally {
mongoose.connection.close(); // Close the database connection
}
}
saveFruitAndPerson();
Hey @Arun_vel,
Welcome to the MongoDB Community.
The use of callback functions has been deprecated in the latest version of Mongoose (version 7.x).
Reference: Mongoose v8.2.2: Migrating to Mongoose 7
If you are using Mongoose 7.x+, please modify the functions that use a callback by switching to the Promise or async/await syntax.
If you have any further questions or concerns, feel free to ask.
Regards,
Kushagra