【问题标题】:Mongoose update not persisting猫鼬更新不持久
【发布时间】:2016-01-29 11:46:31
【问题描述】:

使用 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));
  });
});

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
}
> 

更新: 更改类型字段后,仍然没有成功。这次我只是想推{ $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

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    这里。这是类似的代码,它正在工作。 findbyidandupdate 需要添加一个 "new : true" 可选参数。否则,您会将旧文档退回给您。

    var express = require("express");
    var app = express();
    var mongoose = require("mongoose");
    
    mongoose.connect("mongodb://localhost/population");
    
    var db = mongoose.connection;
    
    db.on("error", console.error.bind(console, "connection error:"));
    db.once("open", function(){
        var mongoose = require("mongoose");
    
        var userSchema = new mongoose.Schema({
            firstname : String,
            lastname : String,
            pets : []
        })
        var userModel = mongoose.model("User", userSchema);
    
        var bob = new userModel({
            "firstname" :"bob",
            "lastname" : "Smith",
            "pets" : [
                {name : "apple", type : "dog"},
                {name : "felix", type : "cat"}
            ]
        })
    
        bob.save(bob, function(err, user){
            console.log(user)
        });
    
      userModel.findOneAndUpdate(
            {firstname : "bob"}, 
            {$push : {"pets" : {name : "pear", type : "pig"}}},
             //THE MOST IMPORTANT PART ADD new : true
            {safe : true, upsert : true, new : true},
            function(err, model){
                console.log(model);
            }
      )
    
    })//once
    
    
    app.listen(3000, function(){
        console.log("listening on port: " , 3000)
    })
    

    【讨论】:

      【解决方案2】:

      真正的原因是pets数组中使用的type不正确。其实type是mongoose的一个关键字,用来标记Schema Type。

      如果将type 更改为type1 如下架构

      var UserSchema = new mongoose.Schema({
          // ....
          pets: [{name: String, type1: String}],
      });
      

      已保存的pets 应如下所示,并带有额外的_id

      "pets" : [
          {
              "name" : "o3",
              "type1" : "t3",
              "_id" : ObjectId("56a5df9adea3071b0de83407")
          },
      

      在这种情况下,我们可以这样做

      UserModel.findOne({ firstName: "bob" }, 'pets', function(err, user) {
        UserModel.update(user, {
          $push: {
            pets: {
                name: "pear", type1: "pig"  
            }
          }
        }, function(err, numAffected, raw) {
      

      结果是

      "pets" : [
          {
              "name" : "o3",
              "type1" : "t3",
              "_id" : ObjectId("56a5df9adea3071b0de83407")
          },
          {
              "type1" : "pig",
              "name" : "pear",
              "_id" : ObjectId("56a5dff3a648301d0db118df")
          }
      ],
      

      【讨论】:

      • 你知道为什么在这里使用$push 不起作用吗?我读到将type 作为密钥可能会导致问题,但我认为这不是这里发生的事情。
      • @jackblank,在我的测试模式中,类型是字符串,所以整个对象作为对象字符串[object Object]推入数组。
      猜你喜欢
      • 2015-08-14
      • 2020-11-13
      • 2012-03-28
      • 2016-05-24
      • 2016-05-14
      • 2018-05-14
      • 2019-08-10
      • 1970-01-01
      相关资源
      最近更新 更多