定义:
编写MongoDB验证,转换和业务逻辑是非常麻烦的. 所以我们发明了Mongoose.
基本用法:
const mongoose = require('mongoose');
// connect
mongoose.connect('mongodb://localhost/test');
// Set to false to make findOneAndUpdate() and findOneAndRemove() use native findOneAndUpdate() rather than findAndModify().
mongoose.set('useFindAndModify', false);
// 定义一个schema
const catSchema = new mongoose.Schema({
name: {
type: String,
minlength: 5,
required: true,
},
});
// 如果你想添加一个key
catSchema.add({
age: 'number',
});
// Exactly the same as the toObject option but only applies when the documents toJSON method is called.
catSchema.set('toJSON', {
transform: (document, returnedObject) => {
returnedObject.id = returnedObject._id.toString(),
delete returnedObject._id;
delete returnedObject._v;
}
});
// 创建一个model
const Cat = mongoose.model('Cat', catSchema);
// POST
const kitty = new Cat({ name: 'Zildjian' }); // create
kitty.save().then(() => console.log('meow'));
// PUT
const id; // ???
Cat.findByIdAndUpdate(id, { name: 'Zildjian2' }, { new: true })
.then((updateCat) => console.log('update:', updateCat))
.catch((error) => console.error(error));
// Delete
Cat.findByIdAndRemove(id).then(() => {});
// GET
Note.find({}).then(notes => {
response.json(notes);
});