const mongoose = require("mongoose");
mongoose.connect("mongodb://demoAdmin:123456@localhost:27017/demo", {
useNewUrlParser: true,
useUnifiedTopology: true
});
const UserSchema = mongoose.Schema({
name: String,
age: Number,
status: Number
});
// 这种写法会默认与users表连接
// const User = mongoose.model("User", UserSchema);
// 这种写法会默认操作第三个参数配置的表
const User = mongoose.model("User", UserSchema, "user");
User.find({}, (err, docs) => {
if (err) {
console.log(err);
return;
}
console.log(docs);
});
CURD
const mongoose = require("mongoose");
mongoose.connect("mongodb://demoAdmin:123456@localhost:27017/demo", {
useNewUrlParser: true,
useUnifiedTopology: true
});
const UserSchema = mongoose.Schema({
name: String,
age: Number,
status: Number
});
const User = mongoose.model("User", UserSchema, "user");
// 查询
User.find({}, (err, docs) => {
if (err) {
console.log(err);
return;
}
console.log(docs);
});
// 新增
const user = new User({
name: "LittleFinger",
age: 33,
status: 0
});
user.save(err => {
if (err) {
console.log(err);
return;
}
console.log("数据新增成功");
});
// 修改
User.updateOne(
{ _id: "5de8bb88023a1d37e881364c" },
{ age: 40, status: 1 },
err => {
if (err) {
console.log(err);
return;
}
console.log("数据修改成功");
}
);
// 删除
User.deleteOne({ _id: "5de8bbb84113d33aa8997e72" }, err => {
if (err) {
console.log(err);
return;
}
console.log("数据删除成功");
});
- 新的语法
router.post("/edit", async (ctx, next) => {
let { _id, name, age } = ctx.request.body;
try {
await User.where({ _id }).update({ name, age });
ctx.body = {
code: 0
};
} catch (e) {
console.log(e);
} finally {
}
});
router.post("/del", async (ctx, next) => {
let { _id } = ctx.request.body;
try {
await User.where({ _id }).remove();
ctx.body = {
code: 0
};
} catch (e) {
console.log(e);
} finally {
}
});
网友评论