2

I am trying to insert a record with nested objects. My intent is to store an event that can have many link posts or image posts under the main event. When I try to save, the top level data is saved but the nested objects only show, "link:[], image:[]" when they should each have three values stored.

var eventSystem = require ("mongoose");
eventSystem.connect('mongodb://localhost/historydb', { useNewUrlParser: true });
var linkPostSchema= new eventSystem.Schema({
    linkurl: String,
    title: String,
    story: String
});
var linkPost = eventSystem.model("linkPost", linkPostSchema);
var imagePostSchema= new eventSystem.Schema({
    src: String,
    title: String,
    story: String
});
var imagePost = eventSystem.model("imagePost", imagePostSchema);
var postSchema= new eventSystem.Schema({
    link: [linkPostSchema],
    image: [imagePostSchema]
});
var Post = eventSystem.model("Post", postSchema);
var eventSchema = new eventSystem.Schema({
    name: String,
    date: Date,
    story: String,
    posts: [postSchema]
});

var Event = eventSystem.model("Event", eventSchema);
var newEvent = new Event({
    name: "MAIN EVENT",
    date: Date.now(),
    story: "main event story"
});

newEvent.posts.push(
     {
         imagePost: {
             src: "first.jpg",
             title: "image post title",
             story: "image post story"
        },
        linkPost: {
            linkurl: "https://youtube.com",
            title: "link post title",
            story: "link post story"
        }
    });

ACTUAL results:

{ _id: 5cf0aea863a51b129a61288f,
  name: 'MAIN EVENT',
  date: 2019-05-31T04:33:44.117Z,
  story: 'main event story',
  posts: [ { _id: 5cf0aea863a51b129a612890, link: [], image: [] } ],
  __v: 0 
 }

EXPECTED results:

{ _id: 5cf0aea863a51b129a61288f,
  name: 'MAIN EVENT',
  date: 2019-05-31T04:33:44.117Z,
  story: 'main event story',
  posts: [ { 
      _id: 5cf0aea863a51b129a612890, 
       link: [linkPost: {
        linkurl: "https://youtube.com",
        title: "link post title",
        story: "link post story"
    }], image: [imagePost: {
         src: "first.jpg",
         title: "image post title",
         story: "image post story"
    }] } ],
  __v: 0 
}

1 Answer 1

1

I got it! the correct syntax should have been:

newEvent.posts.push({
          image: [{
             src: "first.jpg",
             title: "image post title",
             story: "image post story"
         }],
        link: [{
            linkurl: "https://youtube.com",
            title: "link post title",
            story: "link post story"
        }]
});
Sign up to request clarification or add additional context in comments.

Comments

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.