2

How can I create a field in mongoose using a variable name? I've seen some ways to do it using .update(), but I was wondering if there was a way to do it when creating a new document

I have my schema like:

var summariesSchema = mongoose.Schema({
  type: String,
  name: String,
  date: String
})

and my object:

var date = '2015-02-01'
var obj = {
  ios: 100,
  android: 500
}
var doc = {}
doc[date] = obj
var mongoDoc = new Summaries({
  name: 'John',
  type: 'person',
  date: date,
  $doc: doc
})
mongoDoc.save(function(err){
  if(!err) log('done')
  else log(err.toString())
})

But it only saves the fields 'name', 'type' and 'date'.

Can anyone tell me if its possible to do something like that and if so, what am I missing?

3
  • 2
    mongoosejs.com/docs/guide.html#strict (anyone want to write an answer for quick easy rep?) Commented Feb 12, 2015 at 15:57
  • 1
    What are you ultimately trying to do? Using a date for a field name like that is usually a bad idea. Also, you can't start a field name with a $, so $doc isn't valid. Commented Feb 12, 2015 at 16:16
  • @Alex got it right, I wanted to add a field that was not specified in my schema. About the field name, its not a date, its a string representing a date ('2015-02-01') Commented Feb 12, 2015 at 16:53

2 Answers 2

2

Got it.. first part from @Alex is right, just change the schema strict property to false so I can add new fields to my mongo document. For the field name as a variable, I just first created my entire object and then create a new instance of the document:

var summariesSchema = mongoose.Schema({
  type: String,
  name: String,
  date: String
}, { strict: false })

var date = '2015-02-01'
var obj = { 
  name: 'John', 
  type: 'person',
  date: date
}
obj[date] = {
  ios: 100,
  android: 500
}
var mongoDoc = new Summaries(obj)
mongoDoc.save(function(err){
  if(!err) log('Done.')
  else log(err)
}

Success!

EDIT

Three years later ES6 syntax also allows us to do so:

var mongoDoc = await new Summaries({
  name: 'John', 
  type: 'person',
  date: date,
  [date]: { ios: 100, android: 100 }
}).save();
Sign up to request clarification or add additional context in comments.

Comments

0

Change your schema definition to

var summariesSchema = mongoose.Schema({
  type: String,
  name: String,
  date: String
}, { strict: false })

2 Comments

Ok thanks, but one more question, how can I add a field and set the name of that field as a variable. e.g. I want to add the doc object and the name of the field and want to be the string stored in 'date' ('2015-02-01')
you could just do it the same as you have with doc - but use mongoDoc['some-string'] = doc - i think?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.