nodejs在mongodb中修改字符串

时间:2018-10-26 08:21:16

标签: database string mongodb

我正在尝试修改测试:在我的mongodb集合中,使用`

的test.users
User({
    test: "testchange"
})
user.save().then(function () {
    console.log("user has been inserted")
}).catch(function () {
    console.log("Failed")
})

但是它说用户已经被插入,但是它永远不会在数据库上改变。我已经尝试了四个小时了,实际上真的完全迷失了:(这就是架构的样子

    var UserSchema = new mongoose.Schema({
    email: {
        type: String,
        unique: true,
        required: true,
        trim: true
    },
    username: {
        type: String,
        unique: true,
        required: true,
        trim: true
    },
    test: {
        type: String,
        required: true,
    }
});

然后我就用它

var testt = ('still same')
var userData = {
    username: req.body.username,
    test: testt
}

任何帮助将不胜感激。 :)

1 个答案:

答案 0 :(得分:0)

Save仅用于插入文档。使用update通过某些唯一键更改特定字段。我在这里使用过email

检查以下代码示例:

var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

var UserSchema = new mongoose.Schema({
  email: {
      type: String,
      unique: true,
      required: true,
      trim: true
  },
  username: {
      type: String,
      unique: true,
      required: true,
      trim: true
  },
  test: {
      type: String,
      required: true,
  }
});

var User = mongoose.model('UserTest', UserSchema);

function get(){
  var user = new User({
    username: "sd",
    email: "sss@gmail.com",
    test: "tes123"
  });
  user.save().then(function (data) {
    console.log("user has been inserted");
    console.log(data);
    update(); // Calling immediately to quick test only....
  }).catch(function (e) {
    console.log("Failed", e)
  });
}

function update(){
  User.update({email : "sss@gmail.com"}, { test: "testChanged" }, function (err, data) {
    console.log("user has been updated");
    console.log(data);
  });
}

get();

数据库记录:

/* 1 */
{
    "_id" : ObjectId("5bd2db2ebe39c50d99037533"),
    "username" : "sd",
    "email" : "sss@gmail.com",
    "test" : "testChanged",
    "__v" : 0
}

控制台输出:

user has been inserted
{ __v: 0,
  username: 'sd',
  email: 'sss@gmail.com',
  test: 'tes123',
  _id: 5bd2db2ebe39c50d99037533 }
user has been updated
{ ok: 1, nModified: 1, n: 1 }