创建mongoose模式并插入文档

时间:2016-02-27 19:14:00

标签: javascript mongodb mongoose

我是mongo和mongoose的新手。我需要从这个对象

创建模式
trailers: [
{
id: 310131,
results: [
{
id: "564b9086c3a3686026004542",
iso_639_1: "en",
key: "gy_-pupKvxg",
name: "The Witch Official Trailer 1 2016 HD",
site: "YouTube",
size: 1080,
type: "Trailer"
},
{
id: "56aab2b19251417e110008b2",
iso_639_1: "en",
key: "feRupW34rUU",
name: "Trailer 2",
site: "YouTube",
size: 1080,
type: "Trailer"
}
]
}
],

这就是我现在正在做的事情

// My Schema

var movieSchema = new mongoose.Schema({
    ....
    ...
    ..
    .,
    trailers : [
        {
            id: Number,
            results : [
                {
                    id: String,
                    iso_639_1: String,
                    key: String,
                    name: String,
                    site: String,
                    size: Number,
                    type: String,
                }
            ],
            _id : false
        }
    ],
    ....
    ..
    .
});

var Movie = mongoose.model('Movies', movieSchema);

// Insert movie into schema and save to database
movies.forEach(function(m) {
    var movie = new Movie({
        ....
        ...
        ..
        .,
        trailers : m.trailers ? m.trailers : "",
        ....
        ...
        ..
        .
    });

    movie.save(function(err) {
        if(err) console.log('Error on save' + err);
    });
}, this);

但我做错了,任何人都可以发现或告诉我如何将每部电影插入到架构对象中。提前谢谢。

2 个答案:

答案 0 :(得分:0)

根据mongoose subdoc,请尝试使用.pushtrailers推送到movies。以下是示例代码。

movies.forEach(function(m) {
    var movie = new Movie({
        ....
        //trailers : m.trailers ? m.trailers : "",
        ....
    });

    m.trailers.forEach(function(t){
        movie.trailers.push(t);
    });

    movie.save(function(err) {
        if(err) console.log('Error on save' + err);
    });
});

答案 1 :(得分:0)

根据我的说法,这应该是你的架构:

var movieSchema = new mongoose.Schema({
trailers: [
    ....
    ........
    ....
    _id: Number,
    results: [{
        iso_639_1: String,
        key: String,
        name: String,
        site: String,
        size: String,
        type: String
      }]
    ........
    ....
    ]
});

看着你的对象,我的建议是: 您应该将_id数组的trailers字段分配给您当前分配给Number字段的id。并从架构中删除id字段。

_id字段唯一标识集合中的文档。因此,您应该使用它而不是您创建的id字段。

其次,您应该让MongoDB为结果数组对象创建一个_id字段。这就是为什么我没有在结果数组对象中包含_id字段。

接下来,要创建新文档并将其保存在集合中,请使用您的逻辑:

var Movie = mongoose.model('Movies', movieSchema);
// Insert movie into schema and save to database
movies.forEach(function(m) {
var movie = new Movie({
    ....
    ...
    ..
    .,
    (m.trailers) ? trailers = m.trailers : trailers = null,
    ....
    ...
    ..
    .
});

movie.save(function(err) {
    if(err) console.log('Error on save' + err);
});
}, this);

您的逻辑错误在于您尝试使用三元运算符来检查m.trailers是否存在,如果存在,则需要将其分配给预告片数组,否则为null。你正在使用的是:

trailers : m.trailers ? m.trailers : "",

你应该使用的是:

(m.trailers) ? trailers = m.trailers : trailers = null,

请检查并告诉我它是否有效。

相关问题