[英]I get undefined when i try to add an Object from an api to my mongodb atlas db NODE JS
[英].then is undefined when I try to save in MongoDB
我是node.js的新手。 我收到此消息:
TypeError: Cannot read property 'then' of undefined
這是代碼:
router.post("/signup", (req, res) => {
const userRegister = new UserRegister({
_id: new mongoose.Types.ObjectId(),
nickname: req.body.nickname,
email: req.body.password,
password: req.body.password,
level: 0
});
console.log(req.body.nickname + " " + req.body.email + " " + req.body.password);
userRegister
.save()
.then(doc => {
console.log(doc);
res.status(200).json({
message: "User created"
});
})
.catch(err => {
if (err)
console.log("error => " + err)
res.status(409).json({
message: "ERROR"
})
});
});
和架構:
const mongoose = require("mongoose");
const userRegister = mongoose.Schema({
_id : mongoose.Schema.Types.ObjectId,
nickname: String,
email: String,
password: String,
level: Number
});
module.exports = mongoose.model("UserRegister", userRegister);
我不太明白為什么它說“ .then undefined”。 (身體好)
檢查模型是否是有希望的類型,如果不是,則使用回調
assert.ok(Promise的用戶實例); //此返回值或false
router.post("/signup", (req, res) => {
const userRegister = new UserRegister({
_id: new mongoose.Types.ObjectId(),
nickname: req.body.nickname,
email: req.body.password,
password: req.body.password,
level: 0
});
console.log(req.body.nickname + " " + req.body.email + " " + req.body.password);
var user = userRegister.save()
assert.ok(user instanceof Promise);
// if assert.ok return true then use user.then
// else use callback userRegister.save( function(doc){ })
user.then(doc => {
console.log(doc);
res.status(200).json({
message: "User created"
});
})
.catch(err => {
if (err)
console.log("error => " + err)
res.status(409).json({
message: "ERROR"
})
});
});
似乎函數“保存”不會返回Promise。 但是在源代碼中確實如此... https://github.com/Automattic/mongoose/blob/master/lib/model.js#L385
您也可以嘗試“創建”方法。
https://github.com/Automattic/mongoose/blob/master/lib/model.js#L2646
也許會很痛苦:
const result = new SomeModel({...});
new Promise((resolve, reject) => {
// Save model
result.save(err => {
if (err) {
return reject(new Error(`Error with exam ersult save... ${err}`));
}
// Return saved model
return resolve(result);
})
.then(res => {
return res;
})
.catch(err => {
throw new Error(err);
});
router.post("/signup", async (req, res) => {
try{
const userRegister = await UserRegister.create({
_id: new mongoose.Types.ObjectId(),
nickname: req.body.nickname,
email: req.body.password,
password: req.body.password,
level: 0
});
}
catch(err){
console.log("error => " + err)
res.status(409).json({
message: "ERROR"
})
}
console.log(userRegister);
res.status(200).json({
message: "User created"
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.