Home > Mobile >  Mongoose v6.2.7 new Model.save() method not working tried promise, callback and async await in try-c
Mongoose v6.2.7 new Model.save() method not working tried promise, callback and async await in try-c

Time:11-11

Initially, the project was set up with promise support, and all queries used promise like method.then().catch() later some were converted to try-catch with async await. All worked fine until a few weeks ago when all of a sudden some methods stopped working, I have tried converting the methods to many different variations from promise to callback and to try-catch. await new Model(object).save() does not save the record. I am using mongoose.createConnection because I need to connect to two databases.

Here is how I init my DB

const mongoose = require("mongoose");

mongoose.Promise = require('bluebird');

function makeNewConnection(uri, id) {
  const db = mongoose.createConnection(uri);

  db.on("error", function(error) {
    console.log(
      `MongoDB :: connection ${this.name} :: ${id} ${JSON.stringify(error)}`
    );
    db.close().catch(() =>
      console.log(`MongoDB :: failed to close connection ${this.name}`)
    );
  });

  db.on("connected", async function() {
    mongoose.set("debug", function(col, method, query, doc) {
      console.log(
        `MongoDB :: ${
          this.conn.name
        } :: ${id} ${col}.${method}(${JSON.stringify(query)},${JSON.stringify(
          doc
        )})`
      );
    });
    console.log(`MongoDB :: connected ${this.name} :: ${id}`);
    require("../models/notification.model");
    if (process.env.DATABASE_ENV === "local" && id === "cloud") {
      require("../helpers/data.sync.helper");
    }
  });

  db.on("disconnected", function() {
    console.log(`MongoDB :: disconnected ${this.name} :: ${id}`);
  });

  return db;
}

// Use

let local, cloud;

if (process.env?.DATABASE_ENV === "local") {
  // Connect to local database
  local = makeNewConnection(
    `mongodb://${process.env.DATABASE_USER}:${process.env.DATABASE_PASS}@127.0.0.1:27017/Eyemasters?retryWrites=true&authSource=admin&useNewUrlParser=true&useUnifiedTopology=true&w=majority`,
    "local"
  );

  // Connect to cloud database

  cloud = makeNewConnection(
    `mongodb://${process.env.DATABASE_USER}:${process.env.DATABASE_PASS}@64.227.44.132:27017/Eyemasters?retryWrites=true&w=majority`,
    "cloud"
  );

  // Start Database sync helper
} else {
  // Connect to cloud local database

  local = makeNewConnection(
    `mongodb://${process.env.DATABASE_USER}:${process.env.DATABASE_PASS}@localhost:27017/Eyemasters?retryWrites=true&w=majority`,
    "local"
  );
}

module.exports = {
  local,
  cloud
};

And here is one of my models having the issue.

const mongoose = require("mongoose");
mongoose.Promise = require('bluebird');

const { local, cloud } = require("../config/database.config");

const { genId } = require("../helpers/doc.id.generator");

const validator = require("validator");

const UserSchema = mongoose.Schema(
  {
    _id: mongoose.Schema.Types.ObjectId,
    email: {
      type: String,
      required: true,
      unique: true,
      validate: {
        validator: validator.isEmail,
        message: "{VALUE} is not a valid email",
        isAsync: false
      }
    },
    hash: { type: String, bcrypt: true, rounds: 10 },
    firstname: { type: String, required: true },
    lastname: { type: String, required: true },
    phone: { type: String },
    dateOfBirth: { type: Date },
    designation: { type: String },
    role: { type: mongoose.Schema.Types.ObjectId, ref: "Role" },
    passport: { type: String },
    accountDetails: {
      name: String,
      number: Number,
      bank: String
    },
    defaultBranch: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Branch"
    },
    branches: [{ type: mongoose.Schema.Types.ObjectId, ref: "Branch" }],
    createdBy: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User"
    },
    lastModifiedBy: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User"
    },
    webpush: { type: Object },
    inactive: { type: Boolean, default: true },
    approved: { type: Boolean, default: false },
    activationCode: { type: String, unique: true },
    activationExpiresIn: { type: Date }
  },
  { toJSON: { virtuals: true }, timestamps: true }
);

UserSchema.plugin(require("mongoose-bcrypt"));

genId(UserSchema);

UserSchema.pre("save", function(next) {
  if (!this.createdBy) this.createdBy = this._id;
  if (!this.lastModifiedBy) this.lastModifiedBy = this._id;
});

exports.User = exports.User || local.model("User", UserSchema);
exports.OnlineUser = exports.OnlineUser || cloud.model("User", UserSchema);

And Lastly my controller setup;

exports.create = async (req, res) => {
  // Validating entered data

  if (
    !req.body.firstname ||
    !req.body.lastname ||
    req.body.firstname.length < 3 ||
    req.body.lastname.length < 3 ||
    !req.body.email ||
    !req.body.role ||
    req.body.email.length < 3
  ) {
    return res.status(400).send({
      message: "Please fill in all required fields"
    });
  }

  try {
    const user = await User.findOne({
      email: req.body.email.toLowerCase()
    });

    if (user) {
      throw new Error("User with email "   req.body.email   " already exist");
    }

    console.log("Before create");

    let newUser = new User({
      ...req.body,
      activationCode: randtoken.uid(16),
      activationExpiresIn: moment.utc().add(30, "minutes"),
      email: req.body.email.toLowerCase()
    });

    console.log(newUser.save);

    const userData = await newUser.save();

    console.log("Saved");

    let transaction = new DbTransaction({
      transactionType: "insert",
      modelName: "User",
      data: userData,
      clients: [process.env.DATABASE_CLIENT_ID],
      isProcessed: false
    });

    await transaction
      .save()
      .then(d => console.log("Transaction updated successfully"))

    await User.populate(userData, populateQuery, (err, data) => {
      if (err) throw new Error(err);
      return res
        .status(201)
        .send({ message: "User created successfully", user: data });
    });
  } catch (err) {
    console.log(err);
    console.log(err.kind);
    return res.status(500).send({
      message: err.message
    });
  }
};

I have tried different variants of javascript promise based work flow. Like Model.method().then().catch(), async try-await Model.method()-catch and lastly callback Model.method((err, data)=>{ //do something }).

None of the above conbination has worked. My observation is that mongoose just logs "done" into the console for this method but never action is never actually performed.

Your help is greatly appreciated, I have absolutely no idea why this is not working.

Thank you.

CodePudding user response:

Try with:

exports.create = async (req, res) => {
  // Validating entered data

  if (
    !req.body.firstname ||
    !req.body.lastname ||
    req.body.firstname.length < 3 ||
    req.body.lastname.length < 3 ||
    !req.body.email ||
    !req.body.role ||
    req.body.email.length < 3
  ) {
    return res.status(400).send({
      message: 'Please fill in all required fields',
    });
  }

  try {
    const user = await User.findOne({
      email: req.body.email.toLowerCase(),
    });

    if (user) {
      throw new Error('User with email '   req.body.email   ' already exist');
    }

    let newUser = new User({
      ...req.body,
      activationCode: randtoken.uid(16),
      activationExpiresIn: moment.utc().add(30, 'minutes'),
      email: req.body.email.toLowerCase(),
    });

    const userData = await newUser.save();

    let transaction = new DbTransaction({
      transactionType: 'insert',
      modelName: 'User',
      data: userData,
      clients: [process.env.DATABASE_CLIENT_ID],
      isProcessed: false,
    });

    await transaction.save();

    await userData.populate(['defaultBranch', 'branches']); // Here add all fields that you need to populate

    return res
      .status(201)
      .send({ message: 'User created successfully', user: userData });
  } catch (err) {
    return res.status(500).send({
      message: err.message,
    });
  }
};

CodePudding user response:

To all who made effort to assist, Thank you for the help.

I don't know why I am seeing the problem after posting here.

The issue was coming from not calling next in the middleware inside the model setup;

UserSchema.pre("save", function(next) {
  if (!this.createdBy) this.createdBy = this._id;
  if (!this.lastModifiedBy) this.lastModifiedBy = this._id;
});

Replace with;

UserSchema.pre("save", function(next) {
  if (!this.createdBy) this.createdBy = this._id;
  if (!this.lastModifiedBy) this.lastModifiedBy = this._id;
  next();
});

Thank you all once again for your support.

  • Related