我正在尝试将我的模型保存到MongoDB中的数据库中。如果我在运行节点服务器时经历这段代码路径,这段代码实际上是有效的,但是当我尝试使用mocha来测试保存模型时,它不再被保存。我已经确认与mongodb的连接很好。 Thia是输出:
定期保存之前 经常保存后
任何提示或建议将不胜感激。谢谢!
这是我正在进行的测试。
var app = require('./helpers/app');
var User = require('../models/user');
var supertest = require('supertest');
var should = require('should');
var mongoose = require('mongoose');
var MongoUrl = require('./../config.js').mongoUri
var clearDB = require('mocha-mongoose')(MongoUrl);
var testuser = {
username:"admin1",
password:"password",
email:"test@gmail.com",
firstname:"testfirst",
lastname:"testlast",
phonenumber:"4151231234"
};
describe("Routing", function() {
describe("Creating an account", function() {
//To run before each test. DB Clean up is implicitly done after each test.
beforeEach(function(done) {
if (mongoose.connection.db) {
return done();
}
mongoose.connect(dbURI, done);
});
it('User: Creating an account2', function(done){
var newUser = new User({
username: "testusername",
email: "test1@gmail.com",
password: "password",
phoneNumber: "12312312",
firstname: "testfirst",
lastname: "testlast"
});
console.log("before regular save");
newUser.save(function(err){
if(err){
console.log("testerror: " + err);
}
console.log("in regular save");
});
console.log("after regular save");
User.find({}, function(err, docs){
if (err) return done(err);
console.log(docs);
docs.length.should.equal(1);
done();
});
});
});
});
答案 0 :(得分:1)
Model#save
是一个异步功能,因此您必须等到它调用其回调,然后才能通过Model.find
调用找到已保存的文档。
所以将find
检查放在save
回调中:
it('User: Creating an account2', function(done){
var newUser = new User({
username: "testusername",
email: "test1@gmail.com",
password: "password",
phoneNumber: "12312312",
firstname: "testfirst",
lastname: "testlast"
});
console.log("before regular save");
newUser.save(function(err){
if(err){
console.log("testerror: " + err);
return done(err);
}
console.log("in regular save");
console.log("after regular save");
User.find({}, function(err, docs){
if (err) return done(err);
console.log(docs);
docs.length.should.equal(1);
done();
});
});
});