簡體   English   中英

我如何在我的貓鼬模型的這個實例中遍歷這個數組?

[英]How can I loop through this array inside this instance of my mongoose model?

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 循環不起作用

您需要將一個對象傳遞給具有名為post的屬性的Posts構造函數(它可能應該稱為posts ,但會保留下面的原始名稱),並且對於此屬性,您需要指定一個數組。

這個數組可以通過使用Array.prototype.mapPromise.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();

根據您的代碼示例,我不確定您要做什么。 使用模型並嘗試創建時,您可以將其視為新的單一記錄。 如果您嘗試將多個鏈接插入到單個記錄中,我建議用逗號分隔它們,然后將其插入到您的 MongoDB 中。

但是你不能像那樣在你的 Posts 類中迭代。

如果我是你,我會像這樣設置我的文件:

文件:模型/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'
      });
    }
  }
}


然后在你的路由器文件中,你可以使用你的控制器:routes/post.js

const express = require('express');
const router = express.Router();
const { addPost } = require('../controllers/posts');

router
  .route('/')
  .post(addPost);

module.exports = router;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM