database - 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
}
任何帮助将不胜感激。:)
解决方案
保存仅用于插入文档。使用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 }
推荐阅读
- python - 如何让 Python Spyder 输出显示整个输出
- python - 如何使用输入语句打印 for 循环索引?
- azure - Azure B2C Azure Active Directory 使用策略检索令牌中的电子邮件
- hive - 当我为子查询提供别名时,配置单元抛出错误
- reactjs - 如何在 azure devops build 中读取 azure key vault 设置并使其在 Web SPA 中可用
- javascript - 如何正确操作并返回带有节点的文件数组?
- javascript - 时间到期时,项目未从数据库中删除
- angular - Angular 自定义表单控件 - 如果有父 ngForm 实例,如何访问它
- r - 如何计算两组形状文件(.shp)之间的重叠
- reactjs - React - 错误:不变量失败:您不应该在外部使用