MongoDB中$推不工作? [英] $push in MongoDb not working?
问题描述
我的架构是这样的:
VAR exampleSchema = newSchema({
简介:{
经验:[{
EXP:字符串
}]
}
});
这是codeS更新的资料收集方面的经验:
exampleSchema.statics.experience =功能(ID,经验,回调){
VAR更新= {
$推:{
profile.experience:体验
}
}
this.findByIdAndUpdate(ID,更新功能(错误){
如果(ERR){
回调(ERR);
}其他{
回调(NULL);
}
})
我正在错误,如字段'profile.experience必须是一个数组,但String类型的文件{_id:的ObjectId('5653f1d852cf7b4c0bfeb54a')} [对象的对象]
的console.log(经验)等于
{EXP:jlkjlkjlk'}
我的收藏应该是这样的:
经验:
{
EXP:YYYY
},
{
EXP:XXXX}
]
假设你有这个集合:
/ * 1 * /
{
_id:的ObjectId(565425e862760dfe14339ba8),
档案:{
经验:
{
EXP:Experto
}
]
}
}/ * 2 * /
{
_id:的ObjectId(565425f562760dfe14339ba9),
档案:{
经验:{
EXP:Experto
}
}
}/ * 3 * /
{
_id:的ObjectId(5654260662760dfe14339baa),
档案:{
经验:Experto
}
}
如果您尝试(更新DOC / * 2 * /):
db.profile.update(
{_id:的ObjectId(565425f562760dfe14339ba9)},
{$推:{profile.experience:{EXP:中级}}}
)
您得到这个错误:
字段'profile.experience必须是一个数组,但的类型是Object
文件{_id:的ObjectId('565425f562760dfe14339ba9')}
块引用>如果你尝试(更新DOC / * 3 * /):
db.profile.update(
{_id:的ObjectId(5654260662760dfe14339baa)},
{$推:{profile.experience:{EXP:中级}}}
)您将获得:
字段'profile.experience必须是一个数组,但String类型
文件{_id:的ObjectId('5654260662760dfe14339baa')}
块引用>my schema looks like this:
var exampleSchema = newSchema({ profile:{ experience :[{ exp : String }] } });
this is the codes to update experience in profile collection:
exampleSchema.statics.experience = function (id,experience, callback){ var update = { $push: { 'profile.experience': experience } } this.findByIdAndUpdate(id,update,function(err) { if (err) { callback(err); } else { callback(null); } })
I was getting error like
The field 'profile.experience' must be an array but is of type String in document {_id: ObjectId('5653f1d852cf7b4c0bfeb54a')}[object Object]
console.log(experience) is equal to
{ exp: 'jlkjlkjlk' }
my collection should look like this:
experience:[ { exp : "YYYY" }, { exp:"xxxx"} ]
解决方案Imagine that you have this collection:
/* 1 */ { "_id" : ObjectId("565425e862760dfe14339ba8"), "profile" : { "experience" : [ { "exp" : "Experto" } ] } } /* 2 */ { "_id" : ObjectId("565425f562760dfe14339ba9"), "profile" : { "experience" : { "exp" : "Experto" } } } /* 3 */ { "_id" : ObjectId("5654260662760dfe14339baa"), "profile" : { "experience" : "Experto" } }
If you try (update doc /* 2 */):
db.profile.update( { _id: ObjectId("565425f562760dfe14339ba9") }, { $push: { "profile.experience" : { exp : "Intermediate" } } } )
You get this error:
The field 'profile.experience' must be an array but is of type Object in document {_id: ObjectId('565425f562760dfe14339ba9')}
And if you try (update doc /* 3 */):
db.profile.update( { _id: ObjectId("5654260662760dfe14339baa") }, { $push: { "profile.experience" : { exp : "Intermediate" } } } )
You will get:
The field 'profile.experience' must be an array but is of type String in document {_id: ObjectId('5654260662760dfe14339baa')}
这篇关于MongoDB中$推不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!