mongoose学习记录

388 阅读1分钟

语句记录

updateOne

document.updateOne(filter, doc, options, callback)

const res = await Todo.updateOne({
    // 查询条件
    _id: mongoose.Types.ObjectId(req._id)
}, {
    // 要更改的值
    status: req.status === 0 ? 1 : 0
})

$set

$set 用来修改一个指定的键值

  const result = await User.updateOne({
    // 条件
    _id: _id
  }, {$set: {nickname: '叶轻眉', role: ['admin', 'editor']}})

$addToSet

$addToSet 数组 role 中有 editor 则不加入,无则加入

const result = await User.updateOne({
    // 条件
    _id: _id
  }, {$addToSet: {role: 'editor'}})

$inc

$inc 可以对文档的某个值为数字型(只能为满足要求的数字)的键进行增减的操作

const result = await User.updateOne({
    // 条件
    _id: _id
  }, {$inc: {loginTimes: 1}})

更新数组中指定下标元素

let updateParams = {}
updateParams[`voteNumber.${req.selectedIndex}`] = 1
let updateResult = await Vote.updateOne({
  _id
}, {
  $addToSet: {'joinUser': openId},
  $inc: {'joinLength': 1, ...updateParams}
})

统计

await User.count({})

连表查询

await USER.aggregate([
    {
        // 连表查询
        $lookup: {
            from: 'Vote',
            localField: 'openid',
            foreignField: 'openId',
            as: 'test'
        }
    }, {
        // 修改文档的结构----控制返回字段
        $project: {
            _id: 0,
            userType: 1,
            openid: 1,
            userInfo: 1,
            // 计算数组 test 长度 test
            test: {$size: '$test'}
        }    
    }, {
        // 过滤文档,用法类似于 find() 方法中的参数
        $match: {"test": {$gte: 5}}
    },{
        // 跳过条目数
        $skip: 1
        
    },{
        // 限制条目数
        $limit: 1
        
    }
])