本文的内容是基于 Mongoose 开篇继续延续的,需要将 mongoose 的环境搭建好,我这里就直接上的是进行操作 MongoDB 的代码。
增加
单个增加:
User.create({name: 'test666', age: 666}, (err, result) => { if (!err) { console.log('插入成功'); console.log(result); } });
批量增加:
User.create([ {name: 'ls', age: 18}, {name: 'ls', age: 22}, {name: 'ww', age: 21}, {name: 'zl', age: 23}, {name: 'BNTang', age: 33}, ], (err, result) => { if (!err) { console.log('插入成功'); console.log(result); } });
批量增加(Promise的方式):
(async () => { let result = await User.create([ {name: 'ls', age: 18}, {name: 'ls', age: 22}, {name: 'ww', age: 21}, {name: 'zl', age: 23}, {name: 'BNTang', age: 33}, ]); console.log(result); })();
查询
全查询(全字段全数据):
User.find({}, {}, (err, docs) => { if (!err) { console.log(docs); } });
全查询(只展示指定字段):
User.find({}, {_id: 0, name: 1, age: 1}, (err, docs) => { if (!err) { console.log(docs); } });
根据条件查询指定条件的数据:
User.find({name: 'BNTang'}, {_id: 0, name: 1, age: 1}, (err, docs) => { if (!err) { console.log(docs); } });
分页查询:
User.find({}, {_id: 0, name: 1, age: 1}, {skip: 5, limit: 5}, (err, docs) => { if (!err) { console.log(docs); } });
分页查询(Promise):
(async () => { let result = await User.find({}, {_id: 0, name: 1, age: 1}, {skip: 5, limit: 5}); console.log(result); })();