数据中定义的类型如下:
var classSchema = new mongoose.Schema({
classify : {
type: String,
required : true
},
subClassify :[
{
test1 : String,
test2 : String
},
]
},{safe:true});
var classModel = db.model('subClass',classSchema);
var parent = new classModel({
classify: 'JS开发',
subClassify :[
{
test1 : "abc",
test2 : "bdc"
},
]
});
//存入数据库
parent.save(function(err,data){
console.log(data);
})
操作后数据库正常存入数据显示如下:
/* 0 */
{
"classify" : "JS开发",
"_id" : ObjectId("534953412742011430c8b7a4"),
"subClassify" : [
{
"test1" : "123",
"test2" : "456",
"_id" : ObjectId("534953412742011430c8b7a5")
}
],
"__v" : 0
}
现在我的问题是我想操作上面这个条数据,我现在想在 subClassify
这个字段下面增加一条数据,最后数据结果如下:
/* 0 */
{
"classify" : "JS开发",
"_id" : ObjectId("534953412742011430c8b7a4"),
"subClassify" : [
{
"test1" : "123",
"test2" : "456",
"_id" : ObjectId("534953412742011430c8b7a5")
},
{
"test1" : "abc",
"test2" : "def",
"_id" : ObjectId("534953412742011430c8b7a6")
}
],
"__v" : 0
}
我要怎么在 JS 开发这条字段下的 subClassify
的插入一条新的数据呢,我并不是要更新数据,用了各种方法都无法实现,求各路高手指点。谢谢。
6 回复
@owen-hong
我说快了。其实更简单的是直接用$push进行update:
http://stackoverflow.com/questions/11963684/how-to-push-an-array-of-objects-into-an-array-in-mongoose-with-one-call
mongoose的子文档:
http://mongoosejs.com/docs/subdocs.html