我正在尝试使用mongoose更新JSON数组中具体JSON对象中的特定字段。 我的MongoDB包含:
db.users.find({username:"xxx"})
{ "_id" : ObjectId("56cb877e73da764818ec5ded"),..., "githubtoken" : [ { "token" : "9e37axxx", "username" : "xxx", "_id" : ObjectId("572a7cfafe95dec51d9cbf2d") }, { "token" : "4529yyy", "username" : "yyy", "_id" : ObjectId("572a7d3cfe95dec51d9cbf2e") } ] }
我希望获得与"username" : "yyy"
和"user._id" = "56cb877e73da764818ec5ded"
匹配的JSON对象,并使用mongoose将其标记更改为"token" : "4529zzz"
,如下所示:
{ "_id" : ObjectId("56cb877e73da764818ec5ded"),..., "githubtoken" : [ { "token" : "9e37axxx", "username" : "xxx", "_id" : ObjectId("572a7cfafe95dec51d9cbf2d") }, { "token" : "4529zzz", "username" : "yyy", "_id" : ObjectId("572a7d3cfe95dec51d9cbf2e") } ] }
db的架构是:
var userSchema = new Schema({
username : { type: String, required: true },
...
githubtoken: [ { username: {type: String, required: false },
token: {type: String, required: false} }]
});
更新方法:
userSchema.statics.updateuser = function updateuser (query, update, options) {
var promise = new Hope.Promise();
this.findAndUpdate(query, update, options,function(error, user) {
if (error) {
return promise.done(error, null);
}else {
return promise.done(null, user);
}
});
return promise;
};
在我的服务中使用express.js:
query = {$and: [{_id: userid}, {githubtoken: {username:username, token:oldToken}} ]};
update = {$set : {githubtoken:{username:username, token:token}}};
options = { new: true};
User.updateuser(query,update,options).then(function (error,user){
if(error){
return promise.done(error,null);
}else{
}});
但它不起作用,因为删除所有githubtokens数组并只推送新的githubtoken,如下所示:
{ "_id" : ObjectId("56cb877e73da764818ec5ded"),..., "githubtoken" : { "token" : "4529zzz", "username" : "yyy", "_id" : ObjectId("572a7d3cfe95dec51d9cbf2e") } }
有什么想法吗? 非常感谢你:D
答案 0 :(得分:0)
尝试更改这样的查询:
var query = {
{
_id: new ObjectId(userid),
'githubtoken.username': username,
'githubtoken.token': oldToken
}
};
并像这样更新:
var update = {
$set: {
'githubtoken.$.username': username,
'githubtoken.$.token': token
}
};
答案 1 :(得分:0)
您可以使用$
- 位置运算符进行更新:
db.collection('users').update({
"_id": ObjectId("56cb877e73da764818ec5ded"),
"githubtoken.username": "xxx"
}, {
$set: {
"githubtoken.$.username": username,
"githubtoken.$.token": token
}
});
这应该可以解决问题。有关$ - positional operator
https://docs.mongodb.org/manual/reference/operator/update/positional/
答案 2 :(得分:0)
我在page中找到了解决方案:
query = {"githubtoken" :{$elemMatch: {"username": username}}};
update = {$set : {
"githubtoken.$.username": username,
"githubtoken.$.token": token
}};
感谢您的帮助:D