0

I've create a Mongoose model and I wrote some code to test if it works, I tried to save the model and then display all of the models but it doesn't log anything to the console and the model isn't saving.

My testing code:

let User = require('./models/user')(MAI);
let myUser = new User({
  username: 'Admin',
  email: 'admin@example.com',
  password: '123456',
});

await myUser.save();

User.find((err, users) => {
  if(err) console.log(err);
  console.dir(users);
});

My model:

const mongoose = require('mongoose');

const UserSchema = mongoose.Schema({
  user_id: Number,
  username: String,
  email: String,
  password: String,
  verified: { type: Boolean, default: false },
  joindate: { type: Date, default: Date.now },
  postcount: { type: Number, default: 0 },
});

module.exports = function(MAI) {
  UserSchema.plugin(MAI.plugin, {
    model: 'User',
    field: 'user_id',
    startAt: 1,
    incrementBy: 1,
    unique: true
  });
  return mongoose.model('User', UserSchema);
}

And if it's important, mongoose & mai initialization:

mongoose.Promise = require('bluebird');
let connection = mongoose.createConnection('mongodb://localhost:27017/forum');
MAI.initialize(connection);
  • You're sure it's not saving? You checked with the `mongo` cli? – Andy Gaskell Aug 20 '17 at 16:06
  • Well if it's not logging anything than it's not saving... –  Aug 20 '17 at 16:44
  • That's incorrect. Your code is written as if `save` is synchronous. It is not. – Andy Gaskell Aug 20 '17 at 16:53
  • Changed my test and it still doesn't work, and yes, the function that runs the test code is async. –  Aug 20 '17 at 17:01
  • afaik the find method takes an query object as first argument and not a cb so your cb it gets never called as its interpreted as the query object – Johannes Merz Aug 20 '17 at 17:21
  • Nope, in the docs it says that if you pass only a cb it will fetch everything, but just to be sure I've added an empty object as a query and it still doesn't work, the problem is with the saving –  Aug 20 '17 at 17:29

1 Answers1

0

Fixed it, the problem was I required mongoose in the model file when what I should've done was to pass the mongoose from my entry point.