定义:
编写MongoDB验证,转换和业务逻辑是非常麻烦的. 所以我们发明了Mongoose.
基本用法:
const mongoose = require('mongoose');// connectmongoose.connect('mongodb://localhost/test');// Set to false to make findOneAndUpdate() and findOneAndRemove() use native findOneAndUpdate() rather than findAndModify().mongoose.set('useFindAndModify', false);// 定义一个schemaconst catSchema = new mongoose.Schema({name: {type: String,minlength: 5,required: true,},});// 如果你想添加一个keycatSchema.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;}});// 创建一个modelconst Cat = mongoose.model('Cat', catSchema);// POSTconst kitty = new Cat({ name: 'Zildjian' }); // createkitty.save().then(() => console.log('meow'));// PUTconst id; // ???Cat.findByIdAndUpdate(id, { name: 'Zildjian2' }, { new: true }).then((updateCat) => console.log('update:', updateCat)).catch((error) => console.error(error));// DeleteCat.findByIdAndRemove(id).then(() => {});// GETNote.find({}).then(notes => {response.json(notes);});
