Mongoose 实例方法

问题描述 投票:0回答:4

实例方法

// define a schema
const animalSchema = new Schema({ name: String, type: String });

// assign a function to the "methods" object of our animalSchema
animalSchema.methods.findSimilarTypes = function(cb) {
return mongoose.model('Animal').find({ type: this.type }, cb);
};

现在我们所有的动物实例都有一个可用的 findSimilarTypes 方法。

const Animal = mongoose.model('Animal', animalSchema);
const dog = new Animal({ type: 'dog' });

dog.findSimilarTypes((err, dogs) => {
console.log(dogs); // woof

});

我正在阅读猫鼬的文档,但我无法理解这段代码的工作原理。谁能给我解释一下吗

有人解释一下这段代码的流程

javascript node.js mongodb mongoose mongoose-schema
4个回答
2
投票

模式有一个名为

methods
的字段。在该字段中,您可以插入自己的函数,如下所示:

animalSchema.methods.nameOfFunction = function() {
   // Return something here  
   // The `this` keyword refers to the instance of the model
   // I return the type here
   return this.type;
};

稍后当您创建架构实例时,您可以使用它们。

// animalSchema is the Schema we inserted the function into earlier
// create model from instance
const Animal = mongoose.model('Animal', animalSchema);

// Create ab Instance of the model 
// the function added to the methods field gets added
// The dog gets created with type 'dog'
const dog = new Animal({ type: 'dog' });

// Now we can call the function
// the `this` in the function referes to `dog`
var result = dog.nameOfFunction();
// Will put out "dog"
console.log(result)

在您提供的示例中,添加的函数会查找与创建的动物具有相同类型的所有动物。该函数的

cb
参数是回调。当猫鼬完成搜索时调用的另一个函数。


2
投票
// define a schema
const animalSchema = new Schema({ name: String, type: String });

定义动物模式:动物对象保存到数据库时具有哪些字段和特征。

// assign a function to the "methods" object of our animalSchema
animalSchema.methods.findSimilarTypes = function(cb) {
    return mongoose.model('Animal').find({ type: this.type }, cb);
};

定义使用动物配方创建的每个对象还应该有一个名为

findSimilarTypes(callback)
的方法。

const Animal = mongoose.model('Animal', animalSchema);
const dog = new Animal({ type: 'dog' });

dog.findSimilarTypes((err, dogs) => {
    console.log(dogs); // woof
});
  • 当您在模式上调用 mongoose.model() 时,Mongoose 会为您编译一个模型。这允许您创建可以保存到数据库的新对象,但尚未将新对象保存到数据库。
  • 然后创建一个新的动物对象,称为
    dog
    。它的类型为
    'dog'
    请注意,
    dog.findSimilarTypes(cb)
    也存在,如架构中所定义。
  • 调用该方法,它将返回与该对象具有相同类型的所有对象
    dog

补充,解决Shauryan在评论中的附加问题:

您可以检查例如此资源以了解回调函数是什么:回调函数。我会尽力解释您的示例中发生的情况。

findSimilarTypes(cb)
是一个带有单个参数的函数,它也是一个函数。

这里的这个人是一个单一的匿名函数。

(err, dogs) => {
    console.log(dogs); // woof
}

当您将函数作为参数传递时,它称为“回调”。让我们看看当您使用匿名函数作为参数调用

findSimilarTypes(cb)
时会得到什么。

animalSchema.methods.findSimilarTypes = function(cb) {
    return mongoose.model('Animal').find({ type: this.type }, cb);
};

变成这样(当你用匿名函数替换

cb
时):

return mongoose.model('Animal').find({ type: this.type }, (err, dogs) => {
    console.log(dogs); // woof
});

现在归结为 Mongoose 如何定义其 Model.find()。完成后,它使用数据库搜索的错误和结果调用第二个参数。第二个参数是我们之前传递的匿名函数。

需要花一点时间来理解回调。希望这有帮助!


0
投票

我用 Mongoose 文档填补了空白,以便您可以在自己的机器上运行它。这里唯一缺少的部分是添加

url
用于连接。

  // define a schema
const animalSchema = new mongoose.Schema({ name: String, type: String },
  {
    // Assign a function to the "methods" object of our animalSchema through schema options.
    // By following this approach, there is no need to create a separate TS type to define the type of the instance functions.
    methods: {
      findSimilarTypes(cb) {
        return mongoose.model('Animal').find({ type: this.type }, cb);
      }
    }
  });
  
const Animal = mongoose.model('Animal', animalSchema);

// Creating 2 dogs and a cat
const dog = new Animal({ name: 'joe', type: 'dog' });
const dog2 = new Animal({ name: 'joe2', type: 'dog' });
const cat = new Animal({ name: 'bob', type: 'cat'});

mongoose.connect(url)
.then((result) => {
  console.log("connected")
  // Saving our animals to the database
  return Animal.insertMany([dog, dog2, cat])
}).then(() => {
  // Find similar animals to that of `dog`
  dog.findSimilarTypes((err, dogs) => {
    if (err) {
      console.log(err)
    } else {
      console.log(dogs); // you should log two dogs, joe and joe2
    }
  });
})

0
投票

如果使用箭头功能请更改为常规功能

正确:

schema.methods.myMethod = async function () {
  console.log('this', this);
};

错误:

schema.methods.myMethod = async () => {
  console.log('this', this);
};
© www.soinside.com 2019 - 2024. All rights reserved.