Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 用户创建新游戏mongoose时无法更新用户游戏属性_Javascript_Node.js_Mongodb_Mongoose_Mongoose Schema - Fatal编程技术网

Javascript 用户创建新游戏mongoose时无法更新用户游戏属性

Javascript 用户创建新游戏mongoose时无法更新用户游戏属性,javascript,node.js,mongodb,mongoose,mongoose-schema,Javascript,Node.js,Mongodb,Mongoose,Mongoose Schema,我正在开发一个应用程序,用户可以在其中创建、记录和制作琐事游戏User有一个名为games的属性,它是Game实例创建的id的集合。创建Game实例时,在返回新Game实例的响应(JSON)之前,我找到User实例,并使用User模式方法将新创建的Gamesid添加到User的Games属性中的游戏id集合中。当我创建一个游戏时,它似乎起作用了,我能够用反映新添加的游戏id的数组记录用户的实例 但是当我试图通过localhost:4000/users/User\u ID获取User时,games

我正在开发一个应用程序,用户可以在其中创建、记录和制作琐事游戏
User
有一个名为
games
的属性,它是
Game
实例创建的
id的集合。创建
Game
实例时,在返回新
Game
实例的响应(
JSON
)之前,我找到
User
实例,并使用
User
模式方法将新创建的
Games
id添加到
User
的Games属性中的游戏id集合中。当我创建一个游戏时,它似乎起作用了,我能够用反映新添加的
游戏
id的数组记录
用户
的实例

但是当我试图通过
localhost:4000/users/User\u ID
获取
User
时,
games
属性仍然为空

这是我的
用户
型号

const mongoose = require("mongoose");
const validator = require("validator");
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const Schema = mongoose.Schema;

let User = new Schema({
  username: {
     type: String, required: true, trim: true, default: null,
     unique: true
  },
  password: {
     type: String, required: true, trim: true, default: null
  },
  games:{
     type: Array, required: false, default: []
  }
});

User.methods.addGame = async function(id) {
  const user = this;
  var games = user.games;
  games.push(id);
  user.games = games;
  user.save()
  return user
}

module.exports = mongoose.model('User', User);
这是我的根
/users
路由和我的
/users/:id
路由

userRoutes.route('/').get(function(req, res){
  User.find(function(err, users){
    if(err){
       res.status(400).send(err);
    } else {
       res.json(users)
    }
  });
});

userRoutes.route('/:id').get(function(req, res){
   User.findById(req.params.id, function(err, user){
     if(err){
       res.status(400).send(err)
     } else {
       if (user){
          res.status(200).json(user);
       } else {
          res.status(400).send('user not found :(')
       } 
    }
  });
});
这是我的
add
游戏路线

gameRoutes.route('/add').post( async function(req, res){
  try {
    var user = await User.findOne({ _id: req.body.owner })
    let game = new Game(req.body);
    if (!user){
      res.status(400).send('user not found.')
    } else {
      await game.save()
      await user.addGame(game._id);
      if (!game){
        res.status(400).send('game cannot be created');
      } else {
        res.status(200).json(game);
      }
    }
  } catch (error) {
    res.status(500).send(error);
  }
});
最后,这里是我使用
mongoose.set('debug',true)
创建游戏时记录的数据

 Mongoose: users.findOne({ _id: ObjectId("5daca0171febbb25f2c929dd") }, 
 { projection: {} })
 Mongoose: games.insertOne({ questions: [ { id: 0, qTitle: 'When is 
 Independence Day?', qAnswers: [ { aId: 0, aContent: 'July 18th' }, { 
 aId: 1, aContent: 'July 19th' }, { aId: 2, aContent: 'July 30th' }, { 
 aId: 3, aContent: 'July 4th' } ], answer: 3, correct: null }, { id: 1, 
 qTitle: 'When is Christmas Day?', qAnswers: [ { aId: 0, aContent: 
 'July 18th' }, { aId: 1, aContent: 'July 19th' }, { aId: 2, aContent: 
 'December 25th' }, { aId: 3, aContent: 'December 31st' } ], answer: 2, 
 correct: null } ], qTime: null, expDate: null, isPrivate: true, 
 isClosed: false, _id: ObjectId("5db5c2fe96960e318ae8f60f"), name: 
 'poppie', __v: 0 }, { session: null })
 Mongoose: users.updateOne({ _id: ObjectId("5daca0171febbb25f2c929dd"), 
 __v: 19 }, { '$set': { games: [ ObjectId("5db5c2fe96960e318ae8f60f") ] 
 }, 
 '$inc': { __v: 1 } }, { session: undefined })
创建游戏后,如果我转到
/localhost:4000/users
,我会看到
用户的结果列表

 [{
    "username": "matt_cee",
    "password": 
    "$2a$10$/ySrwkMxaHGO24FOEst3NuqpG4iQi78BUCSkl4Hb.RmjTIwynR3l.",
    "games": [
        "5db5c2fe96960e318ae8f60f"
    ]
  }]

如您所见,
games
数组包含新创建的游戏id。我可以在
/add
游戏路径中记录更新的
用户
,但是当访问
/:id
用户路径时,返回的
用户
实例的games属性有一个空数组

我发现问题在于我没有以正确的格式提供属性。下面是我的
游戏
模型是如何建立的

let Game = new Schema({
    owner: { 
          id: { type: mongoose.Schema.Types.ObjectId,
                ref: "User"
          },
          username: {type: String}
        }
    },
    name:{
        type: String
    },
    questions: {
        type: Array
    }
});
问题是我试图通过将新创建的
游戏的id添加到
User.games
来更新
用户
,但是所有者属性没有正确填充,因为我只传递了
用户的id而不是用户名。下面是我更新的游戏模型

let Game = new Schema({
   owner: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true
   },
   name:{
      type: String
   },
   questions: {
      type: Array
   }
})


特别感谢世卫组织的帮助,我能够更好地构建代码并调试数据

mongoose.set('debug',true)
是你的朋友。根据mongoose版本的不同,您应该先
user.markModified('games')
saving@user753642谢谢你的评论。我刚做了些改变,现在看起来像是这样。我还将我的
User
model属性
games
设置为
objectId
的数组。当我向
/users
发出get请求时,我可以为用户获取游戏id,但当我向
users/user\u id
发出请求时,游戏数组为空。你知道为什么它会在一条路线上更新用户而不是在另一条路线上吗?你提供的代码中没有路线
/users
。是否要参考
/add
?顺便说一句,您不同步
game.save
,但在
user.save
成功的情况下仍然返回
game
(这很糟糕)。如果返回
游戏
,请返回保存的
游戏
。只需通过
mongoose.set('debug',true)
在base或再次检查您的播放器是否正确保存。编辑:不要让游戏的假设失败。save在风中消失,作为一个
未处理的PromiserRejection
我没有包括
/users
路线,因为这是一个简单的
获取
给所有用户的路线,我不认为它会相关,但我现在刚刚添加了它
/add
是一种
游戏
路线。正如我刚才所说,我认为
/add
路由正在正确更新
用户
,因为当我通过
/users
获取用户时,我可以看到添加的游戏id。但是当我试图获取单个用户
/users/:id
时,
游戏
属性仍然是空的。同步
game.save()
是什么意思?我还认为
if(!game){…}
语句对于错误处理来说已经足够了。@user753642我实际上刚刚弄明白了。问题在于如何为
游戏
实例设置
所有者
。我可能应该包括
游戏
模型,但我忘了我将
所有者
属性设置为一个对象,其中包含用户的
ObjectId
用户名
,但是当我创建游戏时,我只传递了
ObjectId
,因此所有者没有被正确设置。