const postSchema = new mongoose.Schema({
post:[
{postId: String},
{commentComponent: [
{comment: [String]},
]}
]
})
const Posts = mongoose.model('Posts', postSchema)
这是对mongodb建模的模式的定义
const postLinks = await getPostLinks();
const posts = new Posts({
for (let i = 0; i < postLinks.length; i++) {
const comment = await getComment(postLinks[i]) // here it takes postLinks as a paramaeter to get an array of comment
post: [
{postId: postLinks[i]},
{commentComponent: [
{comment: comment}
]}
]
}
})
const result = await posts.save()
是否有一种在此实例内进行迭代的方法,因为此处的for循环不起作用
答案 0 :(得分:1)
您需要将一个对象传递给Posts
构造函数,并使用一个名为post
的属性(应该将其称为posts
,但在下面保留原始名称),为此属性,您需要指定一个数组。
可以使用Array.prototype.map
和Promise.all
构建此数组:
const post = await Promise.all(
postLinks.map(async (postLink) => {
const comment = await getComment(postLink);
return {
postId: postLink,
commentComponent: [{ comment }],
};
})
);
const posts = new Posts({ post });
const result = await posts.save();
但是,如果您愿意,也可以使用传统的for循环(与您尝试执行的操作类似):
const post = [];
for (let i = 0; i < postLinks.length; i++) {
const comment = await getComment(postLinks[i]);
post.push({
postId: postLinks[i]},
commentComponent: [{ comment }]
});
}
const posts = new Posts({ post });
const result = await posts.save();
答案 1 :(得分:0)
根据您的代码示例,我不确定您要执行的操作。使用模型并尝试创建模型时,可以将其视为新的奇异记录。如果您要在单个记录中插入许多链接,建议您用逗号分隔,然后将其插入您的MongoDB中。
但是您不能这样在Posts类中进行迭代。
如果我是你,我会设置如下文件:
文件:models / Post.js:
const mongoose = require('mongoose');
const PostSchema = new mongoose.Schema({
text: {
type: String,
trim: true,
required: [true, 'Please add some text']
},
link: {
type: String,
required: [true, 'Please add link']
},
createdAt: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('Post', PostSchema);
然后创建一个控制器js文件 文件:controllers / posts.js:
const Post = require('../models/Post');
// @desc Add Post
// @route POST /api/v1/posts
// @access Public
exports.addPost = async (req, res, next) => {
try {
// get post data from the request
// mongo returns a promise so await on it
const post = await Post.create(req.body);
return res.status(201).json({
success: true,
data: post
});
} catch (err) {
if(err.name === 'ValidationError') {
const messages = Object.values(err.errors).map(val => val.message);
return res.status(400).json({
success: false,
error: messages
});
} else {
return res.status(500).json({
success: false,
error: 'Server Error'
});
}
}
}
然后在路由器文件中,可以使用控制器: 路线/post.js
const express = require('express');
const router = express.Router();
const { addPost } = require('../controllers/posts');
router
.route('/')
.post(addPost);
module.exports = router;