Created
February 18, 2020 03:29
-
-
Save sgpinkus/18d5323e4297b09fdd797ed9af7604b4 to your computer and use it in GitHub Desktop.
mongoose-map.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mongoose = require('mongoose'); | |
var getTestConnection = require('./getTestConnection.js'); | |
var UserSchema = new mongoose.Schema({ | |
name: { type: String, required: true }, | |
notes: { | |
type: Map, | |
of: String, | |
default: {}, | |
} | |
}, | |
); | |
async function main() { | |
await getTestConnection(); | |
var User = mongoose.model('users', UserSchema); | |
await User.deleteMany(); | |
let users = ['mary', 'alice', 'bob', 'bill'].map(async (n) => { | |
let user = new User({name: n}); | |
await user.save(); | |
return user; | |
}); | |
users = await Promise.all(users); | |
console.log(users); | |
let mary = await User.findOne({name: 'mary'}); | |
mary.notes.set(String(users[1].id), 'loser'); | |
mary.notes.set(String(users[2].id), 'winner'); | |
await mary.save() | |
console.log(mary); | |
console.log(mary.notes.keys()); | |
console.log('Done'); | |
} | |
main() | |
.then(() => process.exit()) | |
.catch((err) => { console.log(err); console.log('Exiting..'); process.exit() }); | |
/** | |
> db.users.find()[0] | |
{ | |
"_id" : ObjectId("5e4b599af2ff2912f956a456"), | |
"notes" : { | |
"5e4b599af2ff2912f956a457" : "loser", | |
"5e4b599af2ff2912f956a458" : "winner" | |
}, | |
"name" : "mary", | |
"__v" : 0 | |
} | |
> db.users.find()[0].notes instanceof Object | |
true | |
* / |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment