使用mongoose创建更新和保存文档的方法?

Ind*_*ial 29 methods mongoose mongodb node.js express

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

那我该怎么做呢?

我有这样的想法:

mySchema.statics.insertSomething = function insertSomething () {
    return this.insert(() ?
}
Run Code Online (Sandbox Code Playgroud)

小智 58

从静态方法内部,您还可以通过执行以下操作来创建新文档:

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

  • 我最终也这样做了 - 虽然有些事情困扰我创建一个新的(),我不知道该怎么办.有没有其他人有一个很好的方法来做到这一点? (2认同)

ale*_*lex 49

方法用于与模型的当前实例交互.例:

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(..);
})
Run Code Online (Sandbox Code Playgroud)

当您不想与实例交互时,会使用静态,但会执行与模型相关的内容(例如,搜索名为"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;
  });
});
Run Code Online (Sandbox Code Playgroud)

  • `this.save()`,因为`this`会引用`dog` (4认同)
  • @alessioalex - 我注意到它类似于mongoose docs中的示例,但是它们重新指定类型:`return this.model('Animal').find({type:this.type},cb);`我是从来没有理解为什么我们必须在这里使用`model('Animal')`,因为我们将这个方法添加到Animal模式中.据推测它是可选的 - 你知道为什么它在文档中这样写了吗? (3认同)
  • 但是我怎么能在方法中做`dog.save()`呢? (2认同)