在MongoDB中创建数据“ model.save()”后如何响应数据?

时间:2019-02-28 03:27:55

标签: node.js mongodb

我在创建数据后尝试了响应模型,但是它不起作用。它在“ console.log”上显示数据,当我使用“ resolve({})”时它没有响应。

在routers.js中:

const register = require('./functions/register');
module.exports = router => {

router.get('/', (req, res) => res.end('Welcome to Idol Fan With your Idol !'));

//======REGISTER & LOGIN WITH SOCIAL =====
router.post('/socialuser', (req, res) => {
    const social_id = req.body.social_id;
    const token = req.body.token;
    const name = req.body.name;
    const email = req.body.email;
    const photoprofile = req.body.photoprofile;
    const tokenfirebase = req.body.tokenfirebase;

    if (!social_id) {

        res.status(400).json({message: 'Invalid Request !'});

    } else {

        register.registerUser(social_id, name, email, photoprofile, token, tokenfirebase)

            .then(result => {

                res.status(result.status).json({status: result.status, message: result.message, user: result.user})
            })

            .catch(err => res.status(err.status).json({message: err.message}));
    }
});
}

Function Register.js:

const userfan = require('../models/user');
exports.registerUser = (social_id, name, email, photoprofile, token, 
tokenfirebase) =>

new Promise((resolve, reject) => {
    const d = new Date();
    const timeStamp = d.getTime();

    userfan.find({social_id: social_id})
        .then(users => {
            if (users.length == 0) {

                let newUser = new userfan({
                    social_id: social_id,
                    name: name,
                    email: email,
                    photoprofile: photoprofile,
                    token: token,
                    tokenfirebase: tokenfirebase,
                    created_at: timeStamp
                });

                newUser.save()
                    .then(doc => {
                        console.log("run... " + doc);
                        resolve({
                            status: 200,
                            message: 'User Register Sucessfully !',
                            user: doc

                        });
                    })

                    .catch(err => {
                        console.error(err)
                        if (err.code == 11000) {

                            reject({status: 409, message: 'User Already Registered !'});

                        } else {

                            reject({status: 500, message: 'Internal Server Error !'});
                        }
                    });
            } else {
                return users[0];
            }
        })
        .then(usertemp => resolve({status: 200, message: "Login Successfully !", user: usertemp}))

        .catch(err => {
            console.log(err.message);
            reject({status: 500, message: err.message});
        });
});

这是在服务器上运行后的结果: enter image description here enter image description here

结果和上面的代码。我有一个问题,为什么“用户:doc”没有响应?非常感谢!

1 个答案:

答案 0 :(得分:0)

userfan.find.then.then(是同步的,因为不需要等待)在newUser.save.then之前被调用(由于在后台,它等待DB应答,因此是异步的)。

因此,两个resolve都被调用,但是仅考虑了第一个调用,而第一个要调用的是使用usertemp的那个。由于undefined末尾隐含的return undefined,因此此人接受userfan.find.then作为自变量。

您的流量应为:

userfan.find().then(users => {
  if (!users.length) {
    let newUser = ...
    // explicitly return the promise, which will give the created user
    return newUser.save().then(doc => {
      // format and return the value you want
      return {user: doc, message: 'registered'};
    });
  } else {
    // another explicitly returned value, but you already have this
    return {user: users[0], message: 'login'};
  }
  // it's not possible here because we returned before it, but your code reached this point
  // and, implicitly, any function ending with no return does:
  return undefined;
// this .then receives *either* the promise from newUser.save *or* the object from the else block
}).then(structure => {
  structure.status = 200;
  return structure; // here structure is {status: 200, message: 'registered'|'login', user: document}
});

另外,请注意,对箭头函数使用语法快捷方式(在函数主体周围没有花括号)隐含返回单行主体

singleArgument => doSomething();
// is actually *strictly* equivalent to
(singleArgument) => { return doSomething(); }

通过这些书写方式,很容易在需要时失去写return的反射力。