zoukankan      html  css  js  c++  java
  • mongoose 文档(二)Models

    Models是从 Schema 定义编译的构造函数。这些 model 的实例代表能从数据库存储和检索的 documents。数据库中所有document的创建和检索都是这些model处理的。

    1、编译第一个model

    var schema = new mongoose.Schema({ name: 'string', size: 'string' });
    var Tank = mongoose.model('Tank', schema);

    第一个参数是 model 对应的 collection 的单数名称。Mongoose自动寻找model名称的复数版本。因此,如上例,model Tank在数据库中对应tanks collection。model()函数用schema做了一份副本。确保在调用model()之前你已经添加了所有你想要的东西到schema。

    2、构建文档

    documents 是 model 的实例。创建它们并保存到数据库很简单。

    var Tank = mongoose.model('Tank', yourSchema);
    
    var small = new Tank({ size: 'small' });
    small.save(function (err) {
      if (err) return handleError(err);
      // saved!
    })
    
    // or
    
    Tank.create({ size: 'small' }, function (err, small) {
      if (err) return handleError(err);
      // saved!
    })

     注意直到连接到 model 的使用开放为止没有tanks会被创建/删除。在这个案例中我们使用着mongoose.model(),我们打开默认的mongoose collection。

    mongoose.connect('localhost', 'gettingstarted');

    3、查询

    使用Mongoose查询document是容易的,它支持MongoDB丰富的查询语法。documents可以使用每个model方法( find, findById, findOne)或者是静态方法(where)检索。

    Tank.find({ size: 'small' }).where('createdDate').gt(oneYearAgo).exec(callback);

    查看querying章节的详细内容来如何使用Query api。

    4、删除

    model有一种静态删除方法可用于删除所有匹配条件的document。

    Tank.remove({ size: 'large' }, function (err) {
      if (err) return handleError(err);
      // removed!
    });

    5、修改

    每个model有自己的修改方法来修改数据库中的document而不返回到你的应用程序。查看更详细的API文档。

    如果你想修改一个在 db 的 document 并返回它到你的应用程序,使用findOneAndUpdate

    6、更多

    API文档包括需要额外方法可用像 count, mapReduce, aggregate

  • 相关阅读:
    梯度下降法-4.向量化和数据标准化
    梯度下降法-3.实现线性回归中的梯度下降法
    梯度下降法-2.线性回归中的梯度下降法
    梯度下降法-1.原理及简单实现
    线性回归算法-5.更多思考
    TCP/IP协议
    TFTP 服务器
    python3 系统编程进程
    python3 私有化 属性property
    python3 面向对象
  • 原文地址:https://www.cnblogs.com/surahe/p/5180839.html
Copyright © 2011-2022 走看看