【问题标题】:Nodejs MongoDB query doesn't work as expectedNodejs MongoDB 查询无法按预期工作
【发布时间】:2019-07-03 09:56:21
【问题描述】:

谁能解释为什么我的简单更新/设置查询不起作用?我使用带有承诺的猫鼬通过nodejs进行查询。这是我的架构: const mongoose = require('mongoose');

var usersSchema = mongoose.Schema ({
    username:String,
    password:String,
    home_planet:Number,
    last_planet:Number,
    experience:Number,
    money:Number
}, {collection: 'account', versionKey: false});

module.exports = usersSchema;

这是我在数据库中更新/设置值的函数

    const usersSchema = require('./userSchema');
    const mongoose = require('mongoose');
    var userModel = mongoose.model('userModel', usersSchema);

userModel.setUserGold = setUserGold;

        function setUserGold(username, newGold) {
            return userModel.updateOne({username:username}, {
                $set: {experience:newGold}
            });
        }

以及对函数的调用

userModel.setUserGold('test', 500);

其中 test 是用户名,500 是要为该用户名添加到数据库中的 gold 值,但没有设置/更新任何内容?

【问题讨论】:

  • 你的函数是异步的吗?
  • 出于调试目的,请尝试放弃 upsert:true。如果没有文档匹配过滤器,这将创建一个新文档。
  • @Mr.Gandhi 我相信猫鼬查询默认是异步的,不是吗?我试过添加 upsert: true,但还是不行。

标签: node.js mongodb mongoose


【解决方案1】:

我设法通过将 .then() 添加到调用函数来解决问题,例如:

userModel.setUserGold('test', 500)
.then((res) => {
   if (!res) return;
   console.log('player updated');
});

我不知道为什么没有 .then() 就不能工作。我之前尝试过同样的功能,但没有添加 .then() 并且它工作得很好,但是在我添加 .then 之前它突然停止工作() 如果有人能解释这将意味着很多。

【讨论】:

    【解决方案2】:

    您的第一个版本中的问题是,如果 updateOne 函数未提供回调,则您没有提供回调或处理返回的 Promise。从@types/mongoose 看这里的定义:

    updateOne(conditions: any, doc: any, callback?: (err: any, raw: any) => void): Query<any> & QueryHelpers;

    要解决您的问题,请为 updateOne 函数提供回调或像在第二个版本中那样处理 Promise。

    【讨论】:

      猜你喜欢
      • 2017-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多