Node.js 保存Mongoose架构上的数组属性
我有一个mongoose对象模式,看起来类似于以下内容:Node.js 保存Mongoose架构上的数组属性,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我有一个mongoose对象模式,看起来类似于以下内容: var postSchema = new Schema({ imagePost: { images: [{ url: String, text: String }] }); var new_post = new Post(); new_post.images = []; for (var i in req.body.post_content.images) { var im
var postSchema = new Schema({
imagePost: {
images: [{
url: String,
text: String
}]
});
var new_post = new Post();
new_post.images = [];
for (var i in req.body.post_content.images) {
var image = req.body.post_content.images[i];
var imageObj = { url: image['url'], text: image['text'] };
new_post.images.push(imageObj);
}
new_post.save();
我正在尝试使用以下内容创建新帖子:
var postSchema = new Schema({
imagePost: {
images: [{
url: String,
text: String
}]
});
var new_post = new Post();
new_post.images = [];
for (var i in req.body.post_content.images) {
var image = req.body.post_content.images[i];
var imageObj = { url: image['url'], text: image['text'] };
new_post.images.push(imageObj);
}
new_post.save();
但是,一旦我保存了文章,它就会被创建为带有images属性的空数组。我做错了什么?我刚刚做了一些类似的事情,在我的案例中,附加到现有的集合中,请查看此问题/答案。它可能会帮助您: 您的问题是在Mongoose中不能有嵌套对象,只能有嵌套模式。因此,您需要这样做(针对您想要的结构):
新对象中缺少架构的
imagePost
对象。请尝试以下方法:
var new_post = new Post();
new_post.imagePost = { images: [] };
for (var i in req.body.post_content.images) {
var image = req.body.post_content.images[i];
var imageObj = { url: image['url'], text: image['text'] };
new_post.imagePost.images.push(imageObj);
}
new_post.save();
因为您不需要为这些子对象指定模式,所以您可以在父模式中将它们指定为对象文本。