【问题标题】:Creating methods to update & save documents with mongoose?创建使用猫鼬更新和保存文档的方法?
【发布时间】:2012-02-17 18:14:08
【问题描述】:

查看official documentation 后,我仍然不确定如何创建用于在mongoose 中创建和更新文档的方法。

那么我该怎么做呢?

我有这样的想法:

mySchema.statics.insertSomething = function insertSomething () {
    return this.insert(() ?
}

【问题讨论】:

    标签: node.js mongodb methods express mongoose


    【解决方案1】:

    在静态方法中,您还可以通过以下方式创建新文档:

    schema.statics.createUser = function(callback) {
      var user = new this();
      user.phone_number = "jgkdlajgkldas";
      user.save(callback);
    };
    

    【讨论】:

    • 我最终也这样做了——尽管创建一个新的 this() 让我很困扰,但我不知道该怎么做。有没有其他人有很好的方法来做到这一点?
    • 如果你有: var model=bla bla 在静态之前,你可以在里面做 new model() ,因为它触手可及
    • 非常感谢。在我的情况下只有一件事:如果您尝试在猫鼬查询中使用this,它将指向此查询的this,而不是静态实例的this。那是我的问题。
    • 是的,您不能按预期使用“this”,而是使用静态方法:)hydrozen 的答案将是不正确的。 new this() 没问题,但在这种情况下,'this' 将指向错误的对象。
    【解决方案2】:

    方法用于与模型的当前实例进行交互。示例:

    var AnimalSchema = new Schema({
        name: String
      , type: String
    });
    
    // we want to use this on an instance of Animal
    AnimalSchema.methods.findSimilarType = function findSimilarType (cb) {
      return this.find({ type: this.type }, cb);
    };
    
    var Animal = mongoose.model('Animal', AnimalSchema);
    var dog = new Animal({ name: 'Rover', type: 'dog' });
    
    // dog is an instance of Animal
    dog.findSimilarType(function (err, dogs) {
      if (err) return ...
      dogs.forEach(..);
    })
    

    当您不想与实例交互,但要做与模型相关的事情(例如搜索所有名为“Rover”的动物)时,会使用静态。

    如果您想插入/更新模型的实例(到数据库中),那么methods 是要走的路。如果您只需要保存/更新内容,您可以使用 save 函数(已经存在于 Mongoose 中)。示例:

    var Animal = mongoose.model('Animal', AnimalSchema);
    var dog = new Animal({ name: 'Rover', type: 'dog' });
    dog.save(function(err) {
      // we've saved the dog into the db here
      if (err) throw err;
    
      dog.name = "Spike";
      dog.save(function(err) {
        // we've updated the dog into the db here
        if (err) throw err;
      });
    });
    

    【讨论】:

    • 但是我怎么能在一个方法中做dog.save()呢?
    • this.save(),因为this 将引用dog
    • @alessioalex - 我注意到这与 mongoose 文档中的示例相似,但是它们重新指定了类型,例如:return this.model('Animal').find({ type: this.type }, cb); 我一直不明白为什么我们必须在这里使用model('Animal'),因为我们正在将此方法添加到 Animal 模式中。大概它是可选的 - 你知道为什么它在文档中这样写吗?
    • 您使用mongoose.model('Animal', AnimalSchema) 注册模式,然后在您的代码中的其他地方mongoose.model('Animal') 再次获取模型。当您向模型添加某些内容时,您会将其添加到架构中,例如 AnimalSchema.methods.isCatAnimalSchema.statics.findAllDogs
    【解决方案3】:

    不要认为你需要创建一个调用 .save() 的函数。在保存模型之前你需要做的任何事情都可以使用.pre()

    如果您想检查模型是否正在创建或更新,请检查 this.isNew()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-05
      • 2012-03-07
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2018-01-22
      • 2016-10-06
      • 2016-07-30
      相关资源
      最近更新 更多