美文网首页Java 核心技术Node.jsNode.js
关于 mongoose 文档读后感和自己一些小技巧

关于 mongoose 文档读后感和自己一些小技巧

作者: 梁同桌 | 来源:发表于2018-04-01 01:46 被阅读15次

    英文版本地址: http://liangtongzhuo.com/atricle.html?5abfc9c89f54543495c81588

    前言

    最近读了 mongoose 的文档一些心得。

    1. exec() 没啥用!

    Player.find({}).exec()
    Player.find({})
    

    加不加 .exec() 都会返回一个 Promise ,根据文档来看 exec() 返回的 Promise 只有 then 和 catch 这两个方法,find() 返回的 Query 对象, Query 也有 then 和 catch 这两个方法,可以当 Promise 使用。

    mongoose 文档:
    find()  返回的参数 Query
    Model.find()
    Parameters
    [callback] «Function»
    Returns:
    «Query»
    
    Query 原型链有那些方法。
    Query.prototype.then()
    Parameters
    [reject] «Function»
    Returns:
    «Promise»
    Executes the query returning a Promise which will be resolved with either the doc(s) or rejected with the error.
    
    Query.prototype.catch()
    Parameters
    [reject] «Function»
    Returns:
    «Promise»
    Executes the query returning a Promise which will be resolved with either the doc(s) or rejected with the error. Like .then(), but only takes a rejection handler.
    

    包括其它 update create 同理。
    我在 cnode 社区提问,也得到了收获,在对外写接口的时候 exec 有用,因为它返回一个纯净的 Promise 。

    2. 关于数组对象更新问题

    数组内如果存在数据就更新,不存在数组内就插入这条数据。
    数据解构

    {
        _id: "xxx",
        items: [
            {
                id: 1,
                val: 3
            },
             {
                id: 2,
                val: 3
            },
        ]
    }
    

    存在id为1则更新,不存在则插入时,惯用的 $addToSet 全匹配并不能解决这样的问题。
    我看一个博客,目前的做法

    var update = db.a.update({
        _id: 1,
        "items.id": 9
    },{
        "items.$.val": "333"
    });
    
    // 更新的文档数为0,代表不存这条数据,进行插入
    if (update[0] === 0) {
      db.a.update({
        _id: 1,
        // A.这条尤其重要
        "items.id": {
            $ne: 9
        }
      },{
        $push: {
            "items" : { id: 9, val: "123" }
        }
      }
    }
    
    

    虽然 $ne 保证了原子性,更新数据为 0 还是需要两次 IO 操作,还有一种方法就是把 id 当成属性名。

    {
        _id: "xxx",
        items: {
           id_1: {
    
                val: 3
            }
           id_2: {
                val: 3
            }  
        }
    }
    

    数组还是希望存储一些轻量级的东西,也可以当队列和栈来用。

    3. mongoose 模型自动设置时间戳

    我发现 cnode 社区里面开源的源码好多都没用上这个配置。创建数据 createTime 字段会是当前时间戳,更新数据则 updateTime 字段时间戳也会自动更新。

     new mongoose.Schema({
        name: String,
    , {
        timestamps: { createdAt: 'createTime', updatedAt: 'updateTime' }
    });
    
    //也可以设置简单设置
     new mongoose.Schema({
        name: String,
    , {
        timestamps: true
    });
    

    相关文章

      网友评论

        本文标题:关于 mongoose 文档读后感和自己一些小技巧

        本文链接:https://www.haomeiwen.com/subject/ilxocftx.html