在Mongoose回调中保存失败

Failing to save inside a Mongoose callback

本文关键字:保存 失败 回调 Mongoose      更新时间:2023-09-26

更新:我现在知道问题了。这是后续问题。


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

这是我必须遵循的逻辑:

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

我相信除了有问题的mongoose.model("Foo").save(cb);行,其余的代码是没有错误的。但为了以防万一,我把所有东西都包括在这里了。我正在调用保存方法,addFoo(),从路由/索引.js。

// 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;
    }
  });
}

谢谢你帮我调试

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

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

然后您需要创建模型Foo的实例,就像var test = new Foo({creator:'test'})一样,只有在此之后,您才能在实例test上调用.save()