Saving the model to the database only works if the model (mongoose) is in the same file, I don't understand why? The error that occurs when importing a model from another file is as follows:
MongooseError: Operation
users.insertOne()
buffering timed out after 10000ms at Timeout. (/var/www/bhp_2/server/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:149:23)
connection.ts
import { Mongoose } from "mongoose"
//I also tried with es6 import like above
const User = require('../models/users')
const mongoose = new Mongoose()
const conectionOpt = {
useNewUrlParser: true
}
const mongoDbUri = process.env.MONGODB_URI
mongoose.connect(mongoDbUri, conectionOpt).then(()=>{
console.log("MongoDB database connection established successfully");
// if I uncomment the code snippet below and comment out the import model file at the top, then insert to the database will work without a problem
//
// const userShema = new mongoose.Schema({
// first_name: {
// type: String,
// required: true,
// trim: true
// },
// last_name: {
// type: String,
// required: true,
// trim: true
// }
// })
// const User = mongoose.model('User', userShema)
const user = new User({
"first_name" : "Bob",
"last_name": "Test"
})
user.save();
}).catch(err => console.log(err))
users.ts
import mongoose from "mongoose";
const userShema = new mongoose.Schema({
first_name: {
type: String,
required: true,
trim: true
},
last_name: {
type: String,
required: true,
trim: true
}
})
const User = mongoose.model('User', userShema)
module.exports = User
I managed to fix the code to make the model saving work. In the users.ts file instead of re-importing the mongoose object ( import mongoose from "mongoose"
) I used the mongoose variable which I used to connect to the database. I moved mongoose.connect to another file, and added an export of this variable
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.