node.js - user.save() 不在 mongodb 中保存(什么都不做)
问题描述
我试图在 MongoDB 中保存一个用户,但它似乎不起作用。我不知道为什么。我只能告诉你的是,代码正在运行并进入 .pre 保存功能,但它没有进入保存功能承诺。
你能告诉我为什么它没有保存在 base 中吗?
前端提交功能
handleSubmit(user){
console.log(user);
axios.post('http://localhost:3000/signup', user)
.then(data => {
console.log(data);
console.log("OBVIOUSLY I DON'T SEE THIS LOG EITHER");
}
);
}
app.js(node.js 文件)
app.post('/signup', urlencodedParser, function(req, res){
let user = new User(req.body);
user.save().then(() => {
console.log("I DON'T SEE THIS LOG");
});
res.end();
});
user.js(node.js 文件)
UserSchema.pre("save", (next) => {
console.log(this);
console.log("I SEE THIS LOG");
next();
});
const User = mongoose.model('user', UserSchema);
module.exports = User;
解决方案
也许是一个愚蠢的问题,但你在 app.js 中的用户不是 undefined 吗?也许console.log req.body。因为我认为你一开始就不是在做用户。
另一个提示:
改用mongoose的create函数,你会发现一个正在建设文档的例子:
https ://mongoosejs.com/docs/models.html
推荐阅读
- python - Pyomo 热启动
- lambda - 调用匿名/lambda 函数作为属性的 get() 方法的结果
- javascript - 如何比较两个对象并删除重复项
- reactjs - 单击更改状态,然后在延迟后再次更改并在 React 中显示消息
- javascript - 从数组中删除特定注释(JS)
- python - HTTP 调用仅在使用 rest-client 的内部公司网络上失败
- elmish-wpf - 支持 Elmish.WPF 应用程序中的插件架构?
- neural-network - ResNext 架构中的基数与宽度
- c# - 使用 MVC 将 Power BI 报表嵌入网站
- javascript - 在 Jest (Node.js) 中从单例测试静态方法