Сохранить используется только для вставки документа. Используйте 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 }