Mongoose return a empty array when i am trying to use find() function.Can any one help me with this please?
users.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
const userSchema = new Schema({
name: String
});
const user = mongoose.model('user', userSchema, 'users');
module.exports = user;
test_helper.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/user_test');
before((done)=>{
mongoose.connection.once('open',()=>{
console.log('Connected');
}).on('error', ()=>{
console.log('Error');
});
done();
});
beforeEach((done)=>{
mongoose.connection
.collections
.users
.drop(()=>{
done();
});
});
create_user.js
const assert = require('assert');
const User = require('../src/user');
describe('Create a user',()=>{
it('it should create a new user',(done)=>{
let joe = new User({
name : "Joe"
});
joe.save().then(()=>{
assert(!joe.isNew);
done();
});
});
})
reading-users.js
const assert = require('assert');
const User = require('../src/user');
describe('This will read all users', () => {
before((done) => {
joe = new User({name:'joe'});
joe.save().then(() => done());
});
it('It Should find all users named joe', (done) => {
User.findOne({name:"Joe"})
.then((foo)=>{
//assert(users[0]._id.toString()===joe._id.toString());
console.log(foo);
console.log(joe);
done();
});
});
});
=============================log==========================================
(node:3324) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect. Create a user Connected √ it should create a new user (274ms)
This will read all users [] { _id: 5bfa98eb6bd05d0cfc5d639d, name: 'joe', __v: 0 } √ It Should find all users named joe
2 passing (1s)
find()tofindOne()? Being the former returns an array but the other does not. Addmongoose.set('debug', true)at the top of your tests in order to see the output of what is actually being sent to MongoDB. And most importantly "when"!