javascript - 如何使用对象将数据保存到 mongodb 模式
问题描述
我一直在尝试将用户数据保存到 mongodb 模式,示例模式如下,问题是如何在对象中插入数据。请帮助我已经这样做了几个小时
例如 User.js
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
data:{
type: String,
requred: true
},
data2:{
type: String,
requred: true
},
work: {
industry: String,
name: String,
position: String,
},
status:{
type: Boolean,
default: true,
requred: true
},
subscription:{
product: String,
license: String,
price: String,
status: Boolean,
default: false,
renew: Boolean,
default : false
},
date:{
type: Date,
default: Date.now
}
});
const User = mongoose.model('User', UserSchema);
module.exports = User;
样品注册处理
const newUser = new User({
data1,
data2,
work,
subscription
});
newUser.save()
.then(user => {
req.flash('success_mg', 'Successfully Registered your can now Login.');
res.redirect('/login');
})
.catch(err => console.log(err));
解决方案
您想使用 _id 字段,并像这样调用您的架构:
User.findByIdAndUpdate({_id: id}, {...updates}, {new: true})
.then(updated_user=>{ DO SOMETHING... })
...updates将是一个 JSON 对象,其中包含您正在更新的属性的键和值。
推荐阅读
- vba - 工作表选择上的 Excel vba 宏崩溃 - 1 周前工作
- database - 如何从 InfluxDB 获取“MEASUREMENTS”的大小?
- sql - 带有 FROM 子句的更新语句
- java - Scala、Kotlin 和 Java 混合项目在迁移到 gradle 4.0 后在 compileScala 上失败
- javascript - D3使用过渡动画时数据系列渲染不完整
- sql - SQL:如果基表发生更改,临时表是否会在稍后调用时返回不同的结果?
- prestashop - 每第二个产品增加 50% 的折扣 (Prestashop)
- python - PyQT - AttributeError:“MyApp”对象没有属性“TabWidget”
- javascript - 使用 turf.js 在 Mapbox GL JS 中将可拖动点捕捉到矢量瓦片集线
- javascript - 谷歌地图用户位置未加载