Skip to content

Instantly share code, notes, and snippets.

@cmccormack
Created April 16, 2018 01:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmccormack/72eb276d7445055a1baac0ef610ec66f to your computer and use it in GitHub Desktop.
Save cmccormack/72eb276d7445055a1baac0ef610ec66f to your computer and use it in GitHub Desktop.
Mongoose Query and Update Examples
// Example of a schema for a Poll document
const PollSchema = new mongoose.Schema({
createdBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
createdTime: {
type: String,
required: true
},
title: {
type: String,
required: true
},
shortName: {
type: String,
required: true
},
choices: [{
index: Number,
choice: String,
votes: Number
}],
voters: [{
votedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
datevoted: Date,
choiceIndex: Number
}]
})
// Creating model from PollSchema
const Poll = mongoose.model('Poll', PollSchema, 'polls')
// Example document
{
//...
title: "How do you like your coffee",
choices: [
{
choice: 'Regular',
votes: 5
},
{
choice: 'Decaf',
votes: 1
}
]
}
// Search for a single document by _id then pull an object out of an Array within the document
Poll
.findOne({ _id: poll._id })
.update({ $pull: { 'choices': { 'choice': 'Decaf' } } }) //<== Remove object from choices
.exec(console.error)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment