简体   繁体   English

如何使用Mongoose + Express.js存储数组?

[英]How to store an array with Mongoose + Express.js?

I'm new on MongoDB and I wanted to store an array. 我是MongoDB的新手,我想存储一个数组。

Here's an example of what I want 这是我想要的例子

question : {
    question : "My question",
    answer   : "My answer",
    subQuestions : 
    [0] {
        question: "My sub question",
        answer  : "My sub answer"
    },
    [1] {
        question: "My other sub question", 
        answer  : "My other sub answer"
    }
}

But I didn't succeed to put multiple entries in subQuestions. 但是我没有成功在subQuestions中放置多个条目。 I got this instead : 我得到了这个:

question : {
    question : "My question",
    answer   : "My answer",
    subQuestions : {
        question {
            [0] : "My sub question",
            [1] : "My other sub question"
        },
        answer {
            [0] : "My sub answer",
            [1] : "My other sub answer"
        }
    }
}

What I have actually is hard to process in front and I really wanted to have what I've showed in the first bloc. 我实际上很难在前面处理这些东西,我真的很想拥有我在第一集团中所展示的东西。

This is my actual Schema : 这是我的实际架构:

var Questions = new Schema({
    question: { type: String },
    answer  : { type: String },
    subQuestions : {
        question : [String],
        answer   : [String]
    }
});

And my saving script : 还有我的保存脚本:

var q = new Questions;
q.subQuestions.question = ["My sub question", "My other sub question"];
q.subQuestions.answer   = ["My sub answer", "My other sub answer"];

q.save(function(err){
    console.log(err);
});

Can someone help me with this ? 有人可以帮我弄这个吗 ? I'm on it from awhile so maybe it's just a little thing that I didn't think about. 我已经有一段时间了,所以也许这只是我没想到的一件事。

Thank you very much in advance and don't hesitate to ask me questions. 预先非常感谢您,不要犹豫,问我问题。

You just have to define an array in your schema: 您只需要在模式中定义一个数组:

var Questions = new Schema({
    question: { type: String },
    answer  : { type: String },
    subQuestions : [{
        question : String,
        answer   : String
    }]
});

Note that I changed your curly braces. 请注意,我更改了花括号。

To add a new subquestion you can use push() : 要添加一个新的子问题,可以使用push()

q = new Questions
sq.question = "How are you doing?"
sq.answer = "Great."
q.subQuestions.push(sq)

I didn't test this code but it first assembles a JavaScript object from two strings (this is the sq object) and then pushes it to the array. 我没有测试此代码,但它首先从两个字符串(这是sq对象)组装了一个JavaScript对象,然后将其推入数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM