使用Mongoose Node JS将对象添加到数组

时间:2015-06-01 23:05:12

标签: javascript node.js mongodb express mongoose

我在Mongoose中有一个User类,如下所示:

module.exports = mongoose.model('User',{

    Email: String,
    Password: String,
    Firstname: String,
    Lastname: String,
    Address: String,
    Address_State: String, //index
    Zipcode: Number,

    Cars: [

        {

            Make: String,
            Model: String,
            Year: Number,
            Mileage: Number,
            Vin: String
        }

    ]
});

我在包含

的代码的另一部分中创建了一个用户对象
var user = new User({
    Email: email,
    Firstname: firstname,
    Lastname: lastname
});

我希望将汽车列表添加到对象中。

我试过

for(var motor in transportation.results) {

           user.Cars.push({

                           Make: motor.make,
                           Model: motor.model,
                           Year: motor.year,
                           Mileage: Number

                            });

}

但我得到的结果是

{
"Email":"derrick@curiousminds.com",
"Firstname":"Derrick",
"Lastname":"Franco",
"_id":"556cdfb06b98604d04d73900",
"Cars":[{"_id":"556cdfb06b98604d04d73901"}]
}

是否有特定的函数或方法将对象添加到mongoose对象中的数组?

2 个答案:

答案 0 :(得分:0)

在将数组添加到新用户对象的Cars数组字段之前,请先尝试创建数组。请考虑以下事项:

$('#'+vlabel).html('');

答案 1 :(得分:0)

问题是我进行循环的方式,我不得不改变

for(var motor in transportation.results) {

           user.Cars.push({

                           Make: motor.make,
                           Model: motor.model,
                           Year: motor.year,
                           Mileage: Number

                            });

}

到for

中的迭代器循环
for(var i = 0; i < transportation.results.length; i++) {

     user.Cars.push({Make: transportation.results[i].make,
                     Model: transportation.results[i].model,
                     Year: transportation.results[i].year

                     });

}//for loop