1 year ago
#382382
UnsteadyShaggy
Setting value via dynamically generated key in then-block of a returned findOne() promise in Mongoose Node.js
I would like to write a function that can be called whenever I set a default value in my Schema.
At the moment I keep repeating the same code as default value (getting the default SVG from its collection) for each of my parts (e.g. body, ear, head, arm) - which works and looks like this:
arm: { type: partSchema, default: function (){
Arm.findOne({ name: 'default' })
.then(pic => {
this.model.arm = pic;
Pattern.findOne({ name: 'default' })
.then(pic => {
this.model.arm.pattern = pic;
})
.catch(err => {
console.log(err);
});
})
.catch(err => {
console.log(err);
});
What I would like to do is something like this:
function defaultPart(user, part) {
//will turn e.g. part='arm' to 'Arm' so my function can find the apropriate model
var PartModel = mongoose.model(`${part.charAt(0).toUpperCase() + part.slice(1)}`);
PartModel.findOne({ name: 'default' })
.then(pic => {
//model.part does not exist and will not be filled with data, logically
//I'd instead like the function to exchange part with 'arm'
this.model.part = pic;
Pattern.findOne({ name: 'default' })
.then(pic => {
//same concept as above
this.model.part.pattern = pic;
})
.catch(err => {
console.log(err);
});
})
.catch(err => {
console.log(err);
});
}
and then call it within my Schema
arm: {
type: partSchema, default: function () {
defaultPart(user, 'arm');
}},
I've tried to look for answers within Stackoverflow, but the answers mostly revolve around dynamically creating queries like these:
Is there a way to use a variable for the field name in a find() in mongoose?
However I'm not interested in querying my DB, I want to set values within, or rather assign their keys dynamically. I feel like I'm missing something very basic here, something like a template string in Javascript, but I just can't figure out what it is.
Is my idea feasable or will I be stuck with copy-pasting it to all my Schemas (total: 15) separatly?
javascript
node.js
mongoose
mongoose-schema
0 Answers
Your Answer