Created
April 16, 2018 01:14
-
-
Save cmccormack/72eb276d7445055a1baac0ef610ec66f to your computer and use it in GitHub Desktop.
Mongoose Query and Update Examples
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
// 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