0

I want to save an object that has and object and array inside it. But when I end up saving the data in the mongo, it doesnt save a few properties.

like "entityMap": {}, data: {}

body =

{ entityMap: {},
  blocks:
   [ { key: '637gr',
       text: 'Books selected for the you  ',
       type: 'header-four',
       depth: 0,
       inlineStyleRanges: [Array],
       entityRanges: [],
       data: {} } ] }

Heres how my mongo schema structured.

const mongoose = require('mongoose');

const { Schema } = mongoose;

const bookSchema = new Schema({
    body: {
      type: {},
      required: false
    },
    templateName: {
      type: String,
      required: true
    },
    subject: {
      type: String,
      required: true
    },
    googleId: {
      type: String,
      required:true
    },
    createdAt: { type: Date, default: Date.now },
    updatedAt: { type: Date, default: Date.now }
  });

mongoose.model('books', bookSchema);

enter image description here

JP.
  • 1,035
  • 2
  • 17
  • 39

1 Answers1

0

When declaring the property with type {}, mongoose uses the Schema.Types.Mixed type. This way the property may contain anything, but mongoose won't detect changes made to it. You have to manually tell mongoose that the property was modified:

book.body = { foo: { bar: { quux: 'foo' } } }
book.markModified('body');
book.save()

Mongoose SchemaTypes

maxpaj
  • 6,029
  • 5
  • 35
  • 56
  • It didnt work, After making this change, I see no changes in the new objects added in the mongodb. – JP. Dec 18 '17 at 21:46
  • Sorry, I missed the markModified bit, I updated my post – maxpaj Dec 18 '17 at 21:51
  • nope didnt work, Heres my changes const book = new Book({ body, subject, templateName, googleId, dateSent: Date.now() }); try { book.markModified('body'); await book.save(); res.send(book); } catch (err) { console.log(' err while saving =', err ); res.status(422).send(err); } – JP. Dec 18 '17 at 21:56
  • Which version of mongoose are you using? Can you paste your entire schema? By the way I was wrong about having to declare the property as Schema.Types.Mixed, you can simply use `{}` to declare the type. – maxpaj Dec 18 '17 at 22:18
  • {} thats what i had earlier, I've pasted the full mongo schema above in the question. – JP. Dec 18 '17 at 22:26
  • Yeah, sorry about the confusion. Try setting `body` after initializing the object - that matches better with how they use it in the documentation. – maxpaj Dec 18 '17 at 22:32