Skip to content

Instantly share code, notes, and snippets.

@unuigbee
Last active September 12, 2016 13:25
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 unuigbee/96ce5f171c091ae5f080fe4ed3c9f401 to your computer and use it in GitHub Desktop.
Save unuigbee/96ce5f171c091ae5f080fe4ed3c9f401 to your computer and use it in GitHub Desktop.
Setting new array of document references when updating a document
Lets say I had this schema:
const userCommandSchema = mongo.Schema({
objectID: mongo.Schema.ObjectId,
userID: { type: String, required: true },
command: { type: String, required: true },
summary: { type: String },
isFavourite: { type: Boolean, default: false },
},
{ timestamps: true }
);
const UserCommandSequenceSchema = mongo.Schema({
objectID: mongo.Schema.ObjectId,
userID: { type: String, required: true },
commandSequenceTitle: { type: String, required: true },
commandSequenceDescription: { type: String, required: false },
commands: [{ type: mongo.Schema.Types.ObjectId, ref: 'UserCommand' }],
},
{ timestamps: true }
);
// Saving an array of document references within a document is pretty straight forward:
const newUserCommandSequence = new this.UserCommandSequenceModel({
userID,
commandSequenceTitle,
commandSequenceDescription,
});
const arrayOfObjectIDs = [mongo.Types.ObjectId("57d2e31f0098c69c4eefde53"), mongo.Types.ObjectId("57d2e31f0098c69c4eefde57")];
// Add references to documents field property
if (arrayOfObjectIDs.length > 0) {
commandList.forEach((command) => {
newUserCommandSequence.commands.push(command);
});
}
// Then save
return newUserCommandSequence.save()
.then((response) => {
return 'success';
})
.catch((err) => {
console.log(err);
});
// How would I go about updating an array of document references?
const arrayOfObjectIDs = [mongo.Types.ObjectId("57d2e31f0098c69c4eefde53"), mongo.Types.ObjectId("57d2e31f0098c69c4eefde57")];
const query = { _id: id };
// This causes an error saying: "Cannot read property '$isMongooseDocumentArray' of undefined";
const update = { $set: {
commandSequenceTitle,
commandSequenceDescription,
commands
},
};
const options = { new: true };
return this.UserCommandModel.findOneAndUpdate(query, update, options)
.exec()
.then(({ _id, commandSequenceTitle, commandSequenceDescription, commands, createdAt, updatedAt }) => {
})
.catch((err) => {
console.log(err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment