基础的增删改查

# 基础的增删改查

# create 创建

# 插入一条

UserModel.create({
    username: "小米"
}).then((res) => {
    console.log(res); // 返回一个数组
});

# 插入多条

UserModel.create([{
        username: "波波",
    },
    {
        username: "博客",
    },
]).then((res) => {
    console.log(res); // 返回一个数组
});

# 删除

# remove 操作所有

有查询条件则删除全部匹配的,没有查询条件就是清空了集合插入数据后,该集合就被创建了,即便是清空了集合数据,集合不会消失

没有查询条件;
UserModel.remove({}).then((res) => {
    console.log(res); // { n: 14, ok: 1, deletedCount: 14 }
});

有查询条件;
UserModel.remove({
    username: "eee",
    age: 27
}).then((res) => {
    console.log(res); // { n: 1, ok: 1, deletedCount: 1 }
});

# deleteOne 删除一条

如果没有查询条件,则从顶部文档删除一条, 有查询条件,则只会删除匹配到的第一条文档

有查询条件;
UserModel.deleteOne({
    username: "eee",
    age: 27
}).then((res) => {
    console.log(res); //{ n: 1, ok: 1, deletedCount: 1 }
});
没有查询条件;
UserModel.deleteOne({}).then((res) => {
    console.log(res); // { n: 1, ok: 1, deletedCount: 1 }
});

# deleteMany 删除多条,一般配合查询条件

最新版的 mongoose 里推荐使用 deleteMany 逐渐的废弃掉 remove

如果没有查询条件,则清空集合整个,有查询条件,则删除所有匹配项

// 没有查询条件
UserModel.deleteMany({}).then((res) => {
    console.log(res); //{ n: 2, ok: 1, deletedCount: 2 }
});
// 有查询条件
UserModel.deleteMany({
    age: 27
}).then((res) => {
    console.log(res); //{ n: 3, ok: 1, deletedCount: 3 }
});

# 修改/更新 update

# update

没有查询条件,则会更新一条文档,有查询条件,则会更新匹配到的项


# updateOne

没有查询条件按顺序改变第一条,有查询条件改变匹配的第一条


# updateMany

没有查询条件,更新所有文档,有查询条件则会更新匹配到的第一条


# findOneAndUpdate

注意:
findOneAndUpdate方法的第三个参数加上与不加上的区别

加上的话数据返回的是数据库中更新完的数据
UserModel.findOneAndUpdate({}, {
    name: "芒果"
}, {
    new: true
}).then((res) =>
    console.log(res) {
        _id: 5 f7d1ea793311b5a54e96198,
        date: '2020-10-7',
        name: '芒果',
        username: '12383749',
        password: 'njsnkjak',
        __v: 0
    }
);
没有加上的话数据返回的是数据库中没有更新前的数据
UserModel.findOneAndUpdate({}, {
    name: "芒果"
}).then((res) =>
    console.log(res) {
        _id: 5 f7d1ea793311b5a54e96198,
        date: '2020-10-7',
        name: '爱奇艺',
        username: '12383749',
        password: 'njsnkjak',
        __v: 0
    }
);

# 条件查询

# query 条件查询

语法

model.find(query, filter, options, callback(document));
查找大于5的: find({
    age: {
        $gt: 5
    }
})
查找小于25的: find({
    age: {
        $lt: 25
    }
})
查找大于5小于18的: find({
    age: {
        $gt: 5,
        $lt: 18
    }
})
包含1221 的: find({
    age: {
        $in: [12]
    }
})
精确匹配:
或者: find({
    $or: [{
        name: "波波"
    }, {
        age: 21
    }]
})
嵌套字段对象查找: find({
    "info.job": "程序员"
})【 重要】
模糊查询:
find({
    name: {
        $regex: "游"
    }
}) or或 find({
    name: //
})【 重要】

# fliter 过滤

-排除: 当我们要对查询出来的数据排除一些不需要的字段的时候使用。
find({
    name: //
}, "-info -age"):
减号表示过滤的, 不加减号表示只获取该字段数据

# options 高级操作

两种使用:

1. find(query, filter, options)

如果没有使用filter, 需要在第二个参数的地方用一个null占位

2. find(query).setOptions({})

举例: find({}).sort({})

3. 常用的高级操作:

sort排序: 1 正序 - 1 倒叙;
skip: 跳过指定条数的文档数量, 从上往下执行的略过
limit: 指定返回结果的最大数量, 从上往下返回的
lean: 返回普通的 js 对象, 而不是 Mongoose Documents。 建议不需要 mongoose 特殊处理就返给前端的数据都最好使用该方法转成普通 js 对象。
UsersMdel.findOneAndUpdate(reset, {
        loginState: state
    }, {
        new: true
    })
    .lean()

# 分页小例子

const find = (page, numbers) => {
    // 分页查询 page:第几页,number:每页条数
    Books.find({}, null, {
        // sort: { age: 1,},  //对
        skip: (page - 1) * numbers, // 从查询结果头部过滤掉几条
        limit: numbers, // limit从上往下获取几条
    }).then(
        (res) => {
            console.log(`${page}分页数据0`, res);
        },
        (err) => {
            console.log(err);
        }
    );
};
find(2, 3);

#

let {
    UserFood
} = require("../../db/userfood");
let {
    User
} = require("../../db/user");
const formidable = require("formidable");
const path = require("path");
const fs = require("fs");
const {
    userInfo
} = require("os");
const baseurl = "http://8.131.83.251:5678/img/upload/";
// 秀食评论
exports.showfoodcomment = (req, res) => {
    console.log(req.body);
    let {
        userid,
        nickname,
        userportrait,
        commentword,
        foodid
    } = req.body;
    UserFood.findOne({
        _id: foodid
    }, {
        commentlist: 1,
        _id: 0
    }).then((docs) => {
        let newcommentlist = [{
                userid: userid,
                nickname: nickname,
                userportrait: userportrait,
                commentword: commentword,
                huifu: [],
                isshou: [],
                commenttime: new Date().getTime(),
            },
            ...docs.commentlist,
        ];
        UserFood.updateOne({
            _id: foodid
        }, {
            $set: {
                commentlist: newcommentlist
            }
        }).then((doc) => {
            User.findOne({
                openid: userid
            }, {
                comment: 1,
                _id: 0
            }).then(
                (finddoc) => {
                    let newcomment = [commentword, ...finddoc.comment];
                    User.updateOne({
                        openid: userid
                    }, {
                        $set: {
                            comment: newcomment
                        }
                    }).then((updatedoc) => {
                        if (updatedoc.n != 0 && updatedoc.ok != 0) {
                            res.json({
                                code: 200,
                                msg: "评论成功!",
                            });
                        } else {
                            res.json({
                                code: 201,
                                msg: "评论失败!",
                            });
                        }
                    });
                }
            );
        });
    });
};
// 秀食点赞
exports.showfoodiszan = (req, res) => {
    console.log(req.body);
    let {
        type,
        userid,
        foodid,
        userportrait
    } = req.body;
    UserFood.findOne({
        _id: foodid
    }, {
        zanlist: 1,
        _id: 0
    }).then((docs) => {
        if (type == "add") {
            let newzanlist = [{
                    userid: userid,
                    userportrait: userportrait
                },
                ...docs.zanlist,
            ];
            UserFood.updateOne({
                _id: foodid
            }, {
                $set: {
                    zanlist: newzanlist
                }
            }).then((doc) => {
                User.findOne({
                    openid: userid
                }, {
                    thumbs: 1,
                    _id: 0
                }).then(
                    (result) => {
                        let newthumbs = [foodid, ...result.thumbs];
                        User.updateOne({
                            openid: userid
                        }, {
                            $set: {
                                thumbs: newthumbs
                            }
                        }).then((updatedoc) => {
                            if (updatedoc.n != 0 && updatedoc.ok != 0) {
                                res.json({
                                    code: 200,
                                    msg: "点赞成功!",
                                });
                            }
                        });
                    }
                );
            });
        } else {
            let newzanlist = docs.zanlist.filter((item) => {
                return item.userid != userid;
            });
            UserFood.updateOne({
                _id: foodid
            }, {
                $set: {
                    zanlist: newzanlist
                }
            }).then((doc) => {
                User.findOne({
                    openid: userid
                }, {
                    thumbs: 1,
                    _id: 0
                }).then(
                    (openiddoc) => {
                        let newthumbs = openiddoc.thumbs.filter((item) => {
                            return item != foodid;
                        });
                        User.updateOne({
                            openid: userid
                        }, {
                            $set: {
                                thumbs: newthumbs
                            }
                        }).then((thumbsdoc) => {
                            if (thumbsdoc.n != 0 && thumbsdoc.ok != 0) {
                                res.json({
                                    code: 200,
                                    msg: "取消成功!",
                                });
                            }
                        });
                    }
                );
            });
        }
    });
};
// 秀食收藏
exports.showfoodisshou = (req, res) => {
    let {
        type,
        userid,
        foodid
    } = req.body;
    UserFood.findOne({
        _id: foodid
    }, {
        collectionlist: 1,
        _id: 0
    }).then(
        (docs) => {
            if (type == "add") {
                let newcollectionlist = [userid, ...docs.collectionlist];
                UserFood.updateOne({
                    _id: foodid
                }, {
                    $set: {
                        collectionlist: newcollectionlist
                    }
                }).then((doc) => {
                    User.findOne({
                        openid: userid
                    }, {
                        collects: 1,
                        _id: 0
                    }).then(
                        (finddoc) => {
                            let newcollects = [{
                                    type: "showfood",
                                    foodid: foodid
                                },
                                ...finddoc.collects,
                            ];
                            User.updateOne({
                                openid: userid
                            }, {
                                $set: {
                                    collects: newcollects
                                }
                            }).then((updatdoc) => {
                                if (updatdoc.n != 0 && updatdoc.ok != 0) {
                                    res.json({
                                        code: 200,
                                        msg: "收藏成功!",
                                    });
                                }
                            });
                        }
                    );
                });
            } else {
                let newcollectionlist = docs.collectionlist.filter((item) => {
                    return item != userid;
                });
                UserFood.updateOne({
                    _id: foodid
                }, {
                    $set: {
                        collectionlist: newcollectionlist
                    }
                }).then((doc) => {
                    User.findOne({
                        openid: userid
                    }, {
                        collects: 1,
                        _id: 0
                    }).then(
                        (finddoc) => {
                            let newcollects = finddoc.collects.filter((item) => {
                                return item.foodid != foodid;
                            });
                            User.updateOne({
                                openid: userid
                            }, {
                                $set: {
                                    collects: newcollects
                                }
                            }).then((updtadoc) => {
                                if (updtadoc.n != 0 && updtadoc.ok != 0) {
                                    res.json({
                                        code: 200,
                                        msg: "取消成功!",
                                    });
                                }
                            });
                        }
                    );
                });
            }
        }
    );
};
// 秀食详情
exports.showfooddetail = (req, res) => {
    UserFood.find({
        _id: req.body.id
    }).then((docs) => {
        if (docs.length != 0) {
            res.json({
                code: 200,
                data: docs,
            });
        } else {
            res.json({
                code: 201,
                msg: "获取失败!",
            });
        }
    });
};

// 获取秀食
exports.getshowfood = (req, res) => {
    let num = 6;
    let {
        page
    } = req.body;
    UserFood.find({}, null, {
            skip: (page - 1) * num,
            limit: num,
        })
        .exec()
        .then((docs) => {
            if (docs.length != 0) {
                res.json({
                    code: 200,
                    msg: "获取成功",
                    data: docs,
                });
            } else {
                res.json({
                    code: 201,
                    msg: "获取失败",
                });
            }
        });
};
// 上传秀食
let imageList = {};
exports.upshowfood = (req, res) => {
    const form = new formidable.IncomingForm();
    form.uploadDir = path.join(__dirname, "../../public/img");
    form.parse(req, (err, fields, files) => {
        // console.log(fields);
        if (err) {
            res.json({
                code: 501,
                msg: "上传失败",
                errmsg: err,
            });
        }
        const {
            userid,
            imageLen,
            releasetitle,
            releasecontent,
            nickname,
            userportrait,
            imgIndex,
        } = fields;
        const oldPath = files.file.path;
        // console.log(files.file.name)//图片传过来的名字
        const newPath = path.join(path.dirname(oldPath), files.file.name);
        //这里我传回一个下载此图片的Url
        // const downUrl = "https://8.131.83.251:5678/img/" + files.file.name; //这里是想传回图片的链接
        const downUrl = "https://localhost:5678/img/" + files.file.name; //这里是想传回图片的链接
        // 上传图片临时存的数组
        if (!imageList[userid] || imageList[userid].length == 0) {
            imageList[userid] = [];
            imageList[userid].push(downUrl);
        } else {
            imageList[userid].push(downUrl);
        }
        //fs.rename重命名图片名称
        fs.rename(oldPath, newPath, (data) => {
            // console.log("185",data);
        });
        // 当代码存到最后一个时;
        if (Number(imgIndex) + 1 == imageLen) {
            // 往数据库中添加文档
            let data = {
                userid,
                nickname: nickname,
                userportrait: userportrait,
                foodimg: imageList[userid],
                releasetitle,
                releasecontent,
                releasetime: new Date().getTime(),
                zanlist: [],
                collectionlist: [],
                commentlist: [],
            };
            UserFood.create([data]).then((docs) => {
                User.findOne({
                    openid: userid
                }).then((findoc) => {
                    let newshowfood = [docs[0]._id, ...findoc.showfood];
                    User.updateOne({
                        openid: userid
                    }, {
                        $set: {
                            showfood: newshowfood
                        }
                    }).then((result) => {
                        if (result.n != 0 && result.ok != 0) {
                            res.json({
                                code: 200,
                                msg: "发布成功!",
                            });
                        } else {
                            res.json({
                                code: 201,
                                msg: "发布失败",
                            });
                        }
                    });
                });
            });
        } else {
            res.json({
                code: 202,
                msg: "未传完",
            });
        }
    });
};