定义:

编写MongoDB验证,转换和业务逻辑是非常麻烦的. 所以我们发明了Mongoose.

基本用法:

  1. const mongoose = require('mongoose');
  2. // connect
  3. mongoose.connect('mongodb://localhost/test');
  4. // Set to false to make findOneAndUpdate() and findOneAndRemove() use native findOneAndUpdate() rather than findAndModify().
  5. mongoose.set('useFindAndModify', false);
  6. // 定义一个schema
  7. const catSchema = new mongoose.Schema({
  8. name: {
  9. type: String,
  10. minlength: 5,
  11. required: true,
  12. },
  13. });
  14. // 如果你想添加一个key
  15. catSchema.add({
  16. age: 'number',
  17. });
  18. // Exactly the same as the toObject option but only applies when the documents toJSON method is called.
  19. catSchema.set('toJSON', {
  20. transform: (document, returnedObject) => {
  21. returnedObject.id = returnedObject._id.toString(),
  22. delete returnedObject._id;
  23. delete returnedObject._v;
  24. }
  25. });
  26. // 创建一个model
  27. const Cat = mongoose.model('Cat', catSchema);
  28. // POST
  29. const kitty = new Cat({ name: 'Zildjian' }); // create
  30. kitty.save().then(() => console.log('meow'));
  31. // PUT
  32. const id; // ???
  33. Cat.findByIdAndUpdate(id, { name: 'Zildjian2' }, { new: true })
  34. .then((updateCat) => console.log('update:', updateCat))
  35. .catch((error) => console.error(error));
  36. // Delete
  37. Cat.findByIdAndRemove(id).then(() => {});
  38. // GET
  39. Note.find({}).then(notes => {
  40. response.json(notes);
  41. });

文档地址:

http://www.mongoosejs.net/docs/guide.html