Skip to content

Instantly share code, notes, and snippets.

@lineus

lineus/mirik999.js Secret

Created Aug 29, 2018
Embed
What would you like to do?
a simple self contained example demonstrating findByIdAndUpdate
#!/usr/bin/env node
'use strict';
const mongoose = require('mongoose');
mongoose.set('useFindAndModify', false);
mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
const conn = mongoose.connection;
const Schema = mongoose.Schema;
const schema = new Schema({
name: String,
age: Number,
sellers: [{ name: String, count: Number }]
});
const Player = mongoose.model('player', schema);
const player1 = new Player({
name: 'test',
age: 18,
sellers: [{ name: 'EA', count: 400 }, { name: 'Steam', count: 100 }]
});
function sellerCountChanged(p, s, n) {
return Player.findOne({ _id: p._id }, (err, player) => {
if (err) { return console.error(err); }
player.sellers.id(s).set('count', n);
return player.save();
});
}
async function run() {
await conn.dropDatabase();
await player1.save();
await sellerCountChanged(player1, player1.sellers[0]._id, 5000);
let doc = await Player.findOne({});
console.log(doc.sellers[0]);
return conn.close();
}
run();
$: ./mirik999.js
{ _id: 5b8712c266b85f359d3a9716, name: 'EA', count: 5000 }
$:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.