Home > Enterprise >  Mongoose model become undefined when exported
Mongoose model become undefined when exported

Time:01-26

I export the model DemandeTransports from this file :

//@/components/database/model/Schema.js
import { Schema } from "mongoose";
import mongoose from "mongoose";

const userSchema = new Schema({
  email: { type: String, index: true, unique: true, required: true },
  password: { type: String, required: true },
  role: { type: String, required: true },
  infos: Map,
});

const Users = mongoose.models?.user || new mongoose.model("user", userSchema);

const demandeTransportSchema = new Schema({
  date: { type: Date, required: true },
  user: { type: Object, required: true },
  values: { type: Object, required: true },
});

const DemandeTransports =
  mongoose.models?.demandeTransport ||
  new mongoose.model("demandeTransport", demandeTransportSchema);

console.log(DemandeTransports.findOne);
export { Users, DemandeTransports };

Which log (on server): [Function: findOne]

But when I try to import the model in this file :

//@/lib/getAllDemandesFromUser.js
import connectMongo from "@/components/database/conn";
import { DemandeTransports } from "@/components/database/model/Schema";

export default function getAllDemandesFromUser(email) {
  console.log("JSON.stringify(DemandeTransports)");
  console.log(JSON.stringify(DemandeTransports));
  connectMongo().catch((error) =>
    res.status(500).json({
      error: "La connection à la bdd mongo a échoué avec l'erreur : "   error,
    })
  );
  const result = DemandeTransports.findOne({ "user.email": email });
  return result;
}

I get TypeError: components_database_model_Schema__WEBPACK_IMPORTED_MODULE_1_.DemandeTransports.findOne is not a function

And DemandeTransports is logged as undefined, and I can't figure out why.

CodePudding user response:

It looks like the issue is with the way you're trying to import the DemandeTransports model from the Schema.js file.

It appears that you're trying to use the DemandeTransports model as if it's a Mongoose model, but it's actually just a plain JavaScript object with no methods like findOne().

One possible solution is to import the DemandeTransports model as a plain object, then pass it to Mongoose's model() function to create a new model that you can use to query the database.

// Schema.js
const demandeTransportSchema = new Schema({
  date: { type: Date, required: true },
  user: { type: Object, required: true },
  values: { type: Object, required: true },
});

export const DemandeTransportSchema = demandeTransportSchema;


// getAllDemandesFromUser.js
import connectMongo from "@/components/database/conn";
import { DemandeTransportSchema } from "@/components/database/model/Schema";
const DemandeTransports = mongoose.model("demandeTransport", DemandeTransportSchema);

export default function getAllDemandesFromUser(email) {
  connectMongo().catch((error) =>
    res.status(500).json({
      error: "La connection à la bdd mongo a échoué avec l'erreur : "   error,
    })
  );
  const result = DemandeTransports.findOne({ "user.email": email });
  return result;
}

Another solution is to use mongoose.connection.model('demandeTransport', demandeTransportSchema) instead of mongoose.model('demandeTransport', demandeTransportSchema)

// Schema.js
const demandeTransportSchema = new Schema({
  date: { type: Date, required: true },
  user: { type: Object, required: true },
  values: { type: Object, required: true },
});

export const DemandeTransports = mongoose.connection.model('demandeTransport', demandeTransportSchema);

This way you can import the model already created and use it directly with the methods like findOne().

Also make sure you are importing the mongoose library, otherwise the connection to the database cannot be established and the model will not be created.

CodePudding user response:

I just understood : My basis error was that I tried to connect to the mongodb while being in client side, which is impossible. I transfered all my call to the db in a getServerSideProps function :

export async function getServerSideProps(context) {
  const session = await unstable_getServerSession(
    context.req,
    context.res,
    authOptions
  );
  // Fetch data from external API
  connectMongo().catch((error) =>
    console.log("Erreur lors de la connection à la bdd : "   error)
  );
  const result = await DemandeTransports.findOne({
    "user.email": session.user.email,
  });

  const result2 = result.toObject();
  console.log(result.toObject());
  // Pass data to the page via props
  return { props: { result2 } };
}

And now it works perfectly fine.

  • Related