使用的MongoDB和貓鼬,我不能得到$推到一個元素追加到我的數組。在我運行這個之後,我檢查了mongo shell並且新的append不在那裏。不知道我做錯了:貓鼬更新不堅持
UserModel.findOne({ firstName: "bob" }, 'pets', function(err, user) {
UserModel.update(user, {
$push: {
pets: {
name: "pear", type: "pig"
}
}
}, function(err, numAffected, raw) {
if (err) console.log(err);
console.log('updated ' + JSON.stringify(numAffected));
});
});
Mongoose: users.ensureIndex({ username: 1 }) { unique: true, background: true }
Mongoose: users.findOne({ firstName: 'bob' }) { fields: { pets: 1 } }
Mongoose: users.update({ pets: [ { type: 'dog', name: 'apple' }, { type: 'cat', name: 'felix' } ], _id: ObjectId("56a53d45a428cbde3c4299f8") }) { '$push': { pets: { name: 'pear', type: 'pig' } } } {}
updated {"ok":1,"nModified":0,"n":0}
> bob = db.users.find()[0]
{
"_id" : ObjectId("56a53d45a428cbde3c4299f8"),
"firstName" : "bob",
"lastName" : "smith",
"username" : "bob123",
"pets" : [
{
"name" : "apple",
"type" : "dog"
},
{
"name" : "felix",
"type" : "cat"
}
],
"__v" : 0
}
>
UPDATE: 改變類型字段,仍然沒有成功後。這次我只是想推{ $push: { pets: "sssss" } }
。
UserModel.findOne({ firstName: "bob" }, 'pets', function(err, user) {
UserModel.update(user,
{ $push: { pets: "sssss" }},
function(err, numAffected, raw) {
if (err) console.log(err);
console.log('updated ' + JSON.stringify(numAffected));
});
});
下面是實際的MongoDB的日誌:
2016-01-29T03:14:37.030+0000 I COMMAND [conn17] command curves.$cmd command: update { update: "users", updates: [ { q: { pets: [ { petType: "pig", name: "pear" } ], _id: ObjectId('56aad0a3ef5848c231ec80ed') }, u: { $push: { pets: "sssss" } }, upsert: false, multi: false } ], ordered: true, writeConcern: { w: 1 } } ntoskip:0 keyUpdates:0 writeConflicts:0 numYields:0 reslen:55 locks:{ Global: { acquireCount: { r: 1, w: 1 } }, Database: { acquireCount: { w: 1 } }, Collection: { acquireCount: { w: 1 } } } protocol:op_query 0ms
你知道爲什麼使用'$ push'在這裏不起作用嗎?我讀過'將'type'作爲關鍵字可能會導致問題,但我不認爲這是發生在這裏的事情。 –
@jackblank,在我的測試模式中,類型爲字符串,所以整個目的是推入數組作爲對象字符串'[對象的對象]'。 – zangw