[英]Update a specific field in a croncrete JSON object inside an JSON array (Mongoose)
我試圖用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"
匹配的JSON對象"username" : "yyy"
和"user._id" = "56cb877e73da764818ec5ded"
並將其令牌更改為"token" : "4529zzz"
使用"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
嘗試像這樣更改查詢:
var query = {
{
_id: new ObjectId(userid),
'githubtoken.username': username,
'githubtoken.token': oldToken
}
};
並像這樣更新:
var update = {
$set: {
'githubtoken.$.username': username,
'githubtoken.$.token': token
}
};
您可以使用$
- 位置運算符進行更新:
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/的使用的更多細節
我在這個頁面找到了解決方案:
query = {"githubtoken" :{$elemMatch: {"username": username}}};
update = {$set : {
"githubtoken.$.username": username,
"githubtoken.$.token": token
}};
謝謝你的幫助:D
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.