【问题标题】:Failing to save inside a Mongoose callback未能在 Mongoose 回调中保存
【发布时间】:2016-01-11 12:04:37
【问题描述】:

更新:我现在知道问题所在了。这是follow-up question


我正在使用 Mongoose 和 MongoDB 的 MMEAN 堆栈。我在save() 上收到TypeError: undefined is not a function 错误,因为我试图在回调中使用 Mongoose 保存到 MongoDB。不知道如何正确保存。

这是我必须遵循的逻辑:

  1. 检查 Foo 集合是否为空
  2. 如果 Foo 为空,则保存新的 Foo 文档
  3. 如果 Foo 不为空,则不要保存新的 Foo 文档

我相信除了有问题的mongoose.model("Foo").save(cb); 行之外的其余代码都没有错误。但以防万一,我已将所有内容都包含在这里。我正在从 routes/index.js 调用保存方法 addFoo()

// routes/index.js - No errors here
router.post('/foo', function(req, res, next){
  var foo = new Foo(req.body);
  foo.addFoo(function(err, bid){
    if(err){ return next(err); }
    res.json(foo);
  });
});

// models/Foo.js - THE ERROR IS IN HERE

var mongoose = require('mongoose');
var FooSchema = new mongoose.Schema({
  creator: String
});
mongoose.model('Foo', FooSchema);

FooSchema.methods.addFoo = function(cb){

  // finds all documents of Foo into the "results" array
  this.model("Foo").find(function(err, results){
    if (err){return err;}

    // if the Foo results array is empty
    if (results.length == 0){

      // THE LINE BELOW IS WHERE THE ERROR OCCURS
      // mongoose.model("Foo").save(cb);
      //                       ^
      // TypeError: undefined is not a function
      mongoose.model("Foo").save(cb);
      return;
    }
  });
}

感谢您帮我调试。

【问题讨论】:

    标签: javascript node.js mongodb mongoose mean-stack


    【解决方案1】:

    mongoose.model("Foo").save(cb)是错误的。

    您需要一个有效的模型来处理您定义的架构"Foo"var Foo = new mongoose.model('Foo', FooSchema)

    然后您需要创建模型Foo 的实例,例如var test = new Foo({creator:'test'}),然后您才能在实例test 上调用.save()

    【讨论】:

    猜你喜欢
    • 2015-06-14
    • 2013-10-21
    • 2014-04-05
    • 1970-01-01
    • 2015-12-25
    • 2016-02-01
    • 2018-04-27
    • 2016-01-06
    • 2014-06-20
    相关资源
    最近更新 更多