mongoose doc code example

Example 1: mongoose find and update prop

var query = {'username': req.user.username};
req.newData.username = req.user.username;

MyModel.findOneAndUpdate(query, req.newData, {upsert: true}, function(err, doc) {
    if (err) return res.send(500, {error: err});
    return res.send('Succesfully saved.');
});

Example 2: model mongoose

const modelName = mongoose.model("collectionname", collectionSchema);

//example
const fruitSchma = new mongoose.Schema ({
  name: String
});
const Fruit = mongoose.model("Fruit", fruitSchema);

Example 3: mongoose add document

const Product = require('../models/product.js');

const product = new Product();
product.save()
		.then(doc => {})
        .catch(err => {});

Example 4: mongoose max record

const maxQuery = Goods.find({}).sort({ price: -1 }).limit(1).then(goods => goods[0].price);

Example 5: mongoose

mongoose initial setup