我无法在Mongoose中保存嵌套模型。我有三个模型,按以下顺序嵌套:
var userSchema = new mongoose.Schema({
googleId: {type: String, unique: true, required: true},
name: {type: String, required: true},
data: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Activity' }]
});
var activitySchema = new mongoose.Schema({
name: String,
active: Boolean,
selected: Boolean,
idle: Boolean,
data: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Data' }]
});
var dataSchema = new mongoose.Schema({
date: String,
time: {type: Number, default: 0},
timestamp: {type: Number, default: 0}
});
当我想要更新User实例时,用户已经创建并存在于我的数据库中。我一直在读,嵌套对象不会自动更新并保存在Mongoose中。检查记录时,样本用户的记录如下
_id: ObjectId("553423830b308818093188ff")
googleId: "XXXXXXXXXXXXXXXXXXXXX"
name: "Sample name"
data: ["ObjectId(5534238c0b30881809318900)"]
我应该如何在数据库中插入数据?如何确保保存嵌套模型?我目前使用的代码如下:
var data;
// "data" is populated with data to create "Activity" and "Data" models
User.findOne({
'googleId': user.googleId
}, function(err, user) {
if (err) {
return done(err);
}
for (var i = 0; i < data.length; i++){
var newActivity = new Activity({
//populate fields from "data"
});
for (var j = 0; j < data[i].data.length; j++){
var newData = new Data({
//populate fields from "data"
});
newActivity.data.push(newData);
}
user.data.push(newActivity);
}
// Save user
user.save(function(err){
if (err) {
console.log(err);
}
});
});