首页 > 解决方案 > nodejs修改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
}

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

标签: databasestringmongodb

解决方案


保存仅用于插入文档。使用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 }

推荐阅读