使用mongodb和mongoose,我无法获得$ push来向我的数组追加一个元素.在我运行之后,我检查了mongo shell并且新的追加不在那里.不确定我做错了什么:
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));
});
});
Run Code Online (Sandbox Code Playgroud)
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}
Run Code Online (Sandbox Code Playgroud)
> 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
}
>
Run Code Online (Sandbox Code Playgroud)
更新:更改类型字段后,仍然没有成功.这次我只想推动{ $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));
});
});
Run Code Online (Sandbox Code Playgroud)
这是实际的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
Run Code Online (Sandbox Code Playgroud)
真正的原因是数组type中使用的pets不正确。实际上,type是 的关键字之一mongoose,用于标记Schema Type。
如果更改type为type1以下架构
var UserSchema = new mongoose.Schema({
// ....
pets: [{name: String, type1: String}],
});
Run Code Online (Sandbox Code Playgroud)
保存的内容pets应如下所示,并带有额外的内容_id
"pets" : [
{
"name" : "o3",
"type1" : "t3",
"_id" : ObjectId("56a5df9adea3071b0de83407")
},
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我们可以执行以下操作
UserModel.findOne({ firstName: "bob" }, 'pets', function(err, user) {
UserModel.update(user, {
$push: {
pets: {
name: "pear", type1: "pig"
}
}
}, function(err, numAffected, raw) {
Run Code Online (Sandbox Code Playgroud)
结果是
"pets" : [
{
"name" : "o3",
"type1" : "t3",
"_id" : ObjectId("56a5df9adea3071b0de83407")
},
{
"type1" : "pig",
"name" : "pear",
"_id" : ObjectId("56a5dff3a648301d0db118df")
}
],
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
667 次 |
| 最近记录: |