mongoose更新:$ set和$ push没有更新任何东西?

时间:2016-06-23 08:26:28

标签: node.js mongodb express mongoose

如何使用$ set和$ push?

更新mongo

我有以下数据:

[ { _id: 57682f69feaf405c51fdf144,
    email: 'testuser1@testdomain.com',
    username: 'testuser' },
  { username: 'sevilayha', _id: 5768d36c4c243de7422f681e, __v: 0 } ]

在我的快递app.js中:

// With Mongoose, everything is derived from a Schema. Let's get a reference to it and define our users.
var userSchema = mongoose.Schema({
    name: String,
    username: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    admin: Boolean,
    location: String,
    meta: {
      age: Number,
      website: String
    },
    created_at: Date,
    updated_at: Date
});

// The next step is compiling our schema into a Model.
var User = mongoose.model('User', userSchema);

app.get("/", function(req, res) {

   var updateQuery = {};

   User.findOne({ username: /^sevilayha/ }, function (err, user) {
    if (err) return console.error(err);
    updateQuery["meta"] = {
      date: Date.now()
    }
    user.update({
      $push: updateQuery,
      $set: { size: 'large' },
      email: 'test@example.com'
    });
    res.status(200).json(user);
  });
  User.find(function (err, users) {
    if (err) return console.error(err);
    console.log(users);
  });

我仍然得到相同的数据。没有更新,设置或推送。我错过了哪些想法?

我在“猫鼬”:“~4.5.1”

1 个答案:

答案 0 :(得分:0)

我更新了我的架构,但我必须添加回调,否则它将无效:

var userSchema = mongoose.Schema({
    name: String,
    username: { type: String, required: true, unique: true },
    password: { type: String, required: false },
    email: String,
    admin: Boolean,
    location: String,
    meta: {
      age: Number,
      website: String
    },
    data: Array,
    created_at: Date,
    updated_at: Date
});

var updateQuery = {};
  User.findOne({ username: /^sevilayha/ }, function (err, user) {
    if (err) return console.error(err);
    updateQuery["data"] = {
      date: Date.now()
    }
    user.update({
      $push: updateQuery,
      $set: { location: 'large' },
      name: 'John',
      email: 'test2@example.com'
    }, function(err, res) {
      if (err) return console.error(err);
      res.status(200).json(res);
    });
  });

有多奇怪!