我正在尝试插入带有嵌套对象的记录。 我的意图是存储一个事件,该事件在主事件下可以具有许多链接或图像。 当我尝试保存时,将保存顶层数据,但是当嵌套对象应分别存储三个值时,它们仅显示“ link:[],image:[]”。
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"
}
});
实际结果:
{ _id: 5cf0aea863a51b129a61288f,
name: 'MAIN EVENT',
date: 2019-05-31T04:33:44.117Z,
story: 'main event story',
posts: [ { _id: 5cf0aea863a51b129a612890, link: [], image: [] } ],
__v: 0
}
预期结果:
{ _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
}
答案 0 :(得分:1)
我明白了! 正确的语法应该是:
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"
}]
});