Node.js 插入嵌套对象但不保存所有数据
我正在尝试插入带有嵌套对象的记录。 我的意图是在主事件下存储一个可以有许多链接帖子或图片帖子的事件。 当我尝试保存时,会保存顶级数据,但嵌套对象仅显示“link:[]、image:[]”,而每个对象都应该存储三个值Node.js 插入嵌套对象但不保存所有数据,node.js,mongoose,Node.js,Mongoose,我正在尝试插入带有嵌套对象的记录。 我的意图是在主事件下存储一个可以有许多链接帖子或图片帖子的事件。 当我尝试保存时,会保存顶级数据,但嵌套对象仅显示“link:[]、image:[]”,而每个对象都应该存储三个值 var eventSystem = require ("mongoose"); eventSystem.connect('mongodb://localhost/historydb', { useNewUrlParser: true }); var linkPostSchema= n
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
}
我明白了!
正确的语法应该是:
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"
}]
});