【问题标题】:assigning mongoose result feild value to vriable in express将猫鼬结果字段值分配给express中的变量
【发布时间】:2017-05-17 14:43:17
【问题描述】:

我正在尝试将来自 momgoose 的字段的值分配给一个变量,该变量将用作另一个模式中另一个字段的值,如下所示。

function getNextSequence() {
    var x = null
    relcounter.findOne({"name":"cabi"},'seq',  function (err, configs) {
    x=configs.seq
     console.log("##"+x)
     })
     console.log(x)

}

X 为空 我也需要这个 x 的值来添加到另一个字段,如下所示

relconf.update( 
                   {name:"css"},
                    { $push: { relations: {id:getNextSequence(),name:req.body.name,divId:"name_div"} } }

基本需要getNextsequence函数返回seq feild的值并赋值给id feild 任何人都可以为 getNextSequence() 建议正确的代码和 null 值的原因

【问题讨论】:

  • 你好。你能展示你的输出吗?
  • m 在打印 x 时为空
  • 类似:##3 和 null
  • 输出绝对正确。 Node.js 是异步的。所以你可以使用回调或 Promise。

标签: node.js express mongoose


【解决方案1】:

将它包装在函数中是没有用的,您必须创建包含回调或 Promises 链接。所以你需要阅读异步 JavaScript https://www.sitepoint.com/javascript-goes-asynchronous-awesome/ 例如:

//callbacks example
...
app.get('/', function(req, res){
    //parse request params
    ...
    relcounter.findOne({"name": name},'seq',  function (err, configs) {
        if(err) {
           throw err;
        }

        res.send(configs.seq);
    });
});

//promise example
...
app.get('/', function(req, res){
    //parse request params
    ...
    relcounter.findOne({"name": name},'seq')
    .then(function(configs){
         res.send(configs.seq);
    })
    .catch(function(err)=>{
       throw err;
    })
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 2014-01-09
    • 1970-01-01
    • 2018-02-17
    • 2011-01-23
    相关资源
    最近更新 更多