【问题标题】:Mongoose Model.find doesn't want to find a documentMongoose Model.find 不想找到文档
【发布时间】:2017-01-13 02:29:36
【问题描述】:

我正在尝试测试我的 Workout 模型,但 Workout.find 查询不返回文档。

这是我的测试:

  1 var assert = require('chai').assert;
  2 var mongoose = require('mongoose');
  3 var database = require('../../config/database').connect;
  4
  5 var Workout = require('../../app/models/user');
  6 var workout: any;
  7
  8 describe('Workout Model', function() {
  9
 10   before(function(done) {
 11     Workout.findOne({
 12       "_id": "57cdb3e3f230e827daa0636b"
 13     }, function(err: any, doc: any) {
 14       console.log(doc);
 15       assert.isNull(err);
 16       workout = doc;
 17       done();
 18     });
 19   });
 20
 21
 22   it('can find a workout', function(done) {
 23     Workout.findOne({
 24       "days": 4,
 25       "minutes": 45,
 26       "experience": "intermediate",
 27       "goal": "gain_muscle"
 28     }, function (err: any, newWorkout: any) {
 29       assert.isNull(err);
 30       console.log(newWorkout);
 31       assert.equal(newWorkout, workout);
 32       done();
 33     });
 34   });
 35
 36 });

测试结果:

Workout Model
null
null
      ✓ can find a workout

这里是猫鼬模式:

  1 var mongoose = require('mongoose');
  2
  3 var Schema = mongoose.Schema;
  4
  5 var workoutSchema = new Schema({
  6
  7   days: Number,
  8   minutes: Number,
  9   experience: String,
 10   goal: String,
 11   workoutSplit: Schema.Types.Mixed
 12 });
 13
 41
 42 module.exports = mongoose.model('Workout', workoutSchema);

数据库配置文件:

  1 var mongoose = require('mongoose');
  2
  3 var uri = 'mongodb://localhost/test'
  4
  5 function connect() {
  6   mongoose.connect(uri);
  7 }
  8
  9 exports.uri = uri;
 10 exports.connect = connect();

这是来自 Robomongo 的数据库图片:

测试通过,但 console.log 输出 null。有人可以帮助我并告诉我我做错了什么吗?

【问题讨论】:

  • 你有什么错误吗?
  • 不。 err 和 newWorkout 都为空。
  • 你能用find()代替findOne吗?
  • 我试过了,它返回一个空数组。
  • 我刚做了。你现在看到问题了吗?

标签: node.js mongodb mongoose mocha.js


【解决方案1】:

看起来您在任何时候都没有连接到数据库。在您的代码中的某个地方,您需要调用mongoose.connect()mongoose.createConnection(),据我所知,您不是。

【讨论】:

  • 我在3 var database = require('../../config/database').connect; 上做,它在另一个模块中。当我尝试将mongoose.connect() 放入测试文件时,它说我正在尝试打开一个未关闭的连接。
  • 当我回答这个问题时,您的配置文件的内容不是您在问题中显示的内容。
【解决方案2】:

使用id查找文档时使用findById方法

Refer here

数据库中的Id字段是objectId类型而不是字符串

【讨论】:

  • 显示配置/数据库文件并尝试在每个回调中打印错误
  • 尝试console.log(database)里面的描述
  • 它说未定义。我刚刚用数据库配置文件更新了问题
  • 尝试将 mongoose.model 存储到变量中并将该变量导出到您的架构文件中
  • 我做到了,但仍然没有帮助。
猜你喜欢
  • 2012-01-19
  • 2021-10-25
  • 2018-05-12
  • 2016-07-30
  • 2016-03-12
  • 2014-02-04
  • 2019-01-02
  • 2016-03-18
  • 2018-03-20
相关资源
最近更新 更多