首页 > 解决方案 > 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;

标签: node.jsmongodbmongoose

解决方案


也许是一个愚蠢的问题,但你在 app.js 中的用户不是 undefined 吗?也许console.log req.body。因为我认为你一开始就不是在做用户。

另一个提示:
改用mongoose的create函数,你会发现一个正在建设文档的例子:
https ://mongoosejs.com/docs/models.html


推荐阅读