如何设置Mongoose模式在MongoDB中存储对象数组?

我目前有一个array ,其中包含嵌套在其中的多个objects

这是格式…

 [ { id: 1, title: 'Squats', video: 'https://www.youtube.com/watch?v=aPYCiuiB4PA' }, { id: 2, title: 'Push-Ups',video: 'https://www.youtube.com/watch?v=aPYCiuiB4PA' }] 

我试图.save()它在我的Schedule模型,看起来像这样…

 var ScheduleSchema = new mongoose.Schema({ schedule: [Object] }) 

当我在服务器端的Schedule控制器中运行下面的代码时, .save()函数给了我一个“成功”的消息(我给它编程),但是当我看着MongoDB数据库时, schedule数组内没有任何内容。

这是保存的信息在数据库中的样子….

 { "_id" : ObjectId("56c28a0d4c92bec03408c077"), "schedule" : [ ], "__v" : 0 } 

我有一种感觉,我的模型是错误的。

模型模式我试过…

1) schedule: []
2) schedule: [Schema.Types.Mixed]

以防万一这是有帮助的,这里是我的.save()函数,当我试图从计划控制器保存所述数据…

 var new_schedule = new Schedule(req.body.info); new_schedule.save(function(err){ if(err){ console.log('err'); }else{ console.log('worked'); } }) 

我build议像这样设置你的模式:

 var ScheduleSchema = new mongoose.Schema({ schedule: [mongoose.Schema.Types.Mixed] }); 

这将是设置它的正确方法。 另一种方法是定义对象,如下所示:

 var ScheduleSchema = new mongoose.Schema({ schedule: [{ id: { type: Number, default: 1 }, title: { type: String, default: '', trim: true }, video: { type: String, default: '', trim: true } }] }); 

此外,它可能不是在服务器端代码的问题。 在使用req.body.info创build新计划之前,您可能需要像这样放置一行:

 console.log(JSON.stringify(req.body, null, 2)); 

这将打印出可读格式的req.body对象,以便确保客户端应用程序正在发送您认为正在获取的信息。