Node.JS Mongodb 查询/创建

金·加布里埃尔森

我有以下 Node.js javascript 函数:

const createOrUpdateProfile = (pProfile) => {
    db.update({facebookId: pProfile.facebookId}, pProfile, {upsert:true}, function (err, profile) {
        if (err) {
            console.log(err);
        };
        console.log("profile " + profile.occupation);
        return profile;
    })
};

该函数是用一个用户配置文件对象调用的,该对象只是一个带有一些用户信息的普通对象。那里没什么特别的。

事实上,该功能会做我想要它做的事情。它要么在 MongoDB 数据库中找到配置文件并更新它,要么在未找到时将其插入到数据库中。

问题是配置文件(新的或更新的)永远不会返回。我猜这与 Node.js 的异步性质有关。

我已经在使用回调函数来捕获配置文件,但似乎不起作用。

我在这里错过了什么?

编辑:

我改变了功能,看起来像你建议的:

const createOrUpdateProfile = (pProfile, callback) => {
db.update({facebookId: pProfile.facebookId}, pProfile, {upsert:true}, function (err, profile) {
    if (err) {
        console.log(err);
    };
    callback(profile);
})

};

我从这样的 graphQL 突变中调用它:

createOrUpdateProfile: (_, { profile }) => {
    Profile.createOrUpdateProfile(profile, (cbProfile) => {
        // do something with the new profile
        console.log(cbProfile.occupation);
    })
},

但 cbProfile 似乎未定义。

我这样做错了吗?

稍后我将不得不研究承诺。我只想先让这个工作。

您不能return在同步函数内进行异步调用。相反,您可以使用回调。像这样:

const createOrUpdateProfile = (pProfile, callback) => {
    db.update({facebookId: pProfile.facebookId}, pProfile, {upsert:true}, function (err, profile) {
        if (err) {
            console.log(err);
        };
        console.log("profile " + profile.occupation);
        callback(profile);
    })
};

然后你可以这样称呼它:

createOrUpdateProfile(pProfile, (profile) => {
    // do something with the new profile
    console.log(profile);
})

如果您不想使用回调,那么Promise是实现此功能的另一种方式。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章