我希望用户能够单击一个按钮,将用户名和id推送到与数据库中的集合关联的数组中,但前提是它们不在该数组中。
我的解决方案是:
var isInGroup = function(user, arr){
var match = arr.indexOf(user);
console.log(">>>>>>>" + match);
if(match === -1){
arr.push(user);
console.log("added user");
} else {
console.log("Already in group");
}
};
当我在控制台中对示例数组进行测试时,这是有效的,但在我查询数据库时却没有。当我在我的应用程序中执行该函数时,即使用户已经在数组中,arr.indexOf = -1。
这是相关代码:
Player.js
var express = require("express"),
router = express.Router({mergeParams:true}),
Game = require("../models/game"),
Player = require("../models/player"),
User = require("../models/user"),
middleware = require("../middleware");
//Add A Player
router.post("/", middleware.isLoggedIn, function(req, res){
//find game
Game.findById(req.body.game, function(err, foundGame){
console.log(">>>>" + foundGame);
if(err){
req.flash("error", "Something went wrong.");
} else {
//create player
Player.create(req.user, function(err, player){
if(err){
console.log(">>>> error" + player);
res.redirect("back");
} else {
player.id = req.user_id;
player.username = req.user.username;
middleware.isInGroup(player, foundGame.players);
foundGame.save();
res.redirect("back");
}
});
}
});
});
游戏架构
var mongoose = require("mongoose");
var gameSchema = new mongoose.Schema({
name:String,
author:{
id:{
type: mongoose.Schema.Types.ObjectId,
ref:"User"
},
username:String,
},
court:{
id:{
type:mongoose.Schema.Types.ObjectId,
ref:"Court"
},
name:String,
},
players:[
{
id:{ type:mongoose.Schema.Types.ObjectId,
ref:"Player",
},
username:String
}
],
time:{
start:String,
end:String
},
date:String,
});
module.exports = mongoose.model("Game", gameSchema)
播放器架构
var mongoose = require("mongoose");
var playerSchema = new mongoose.Schema({
id:{type:mongoose.Schema.Types.ObjectId,
ref:"User"
},
username: String
});
module.exports = mongoose.model("Player", playerSchema);
User Schema
var mongoose = require("mongoose"),
passportLocalMongoose = require("passport-local-mongoose");
var userSchema = new mongoose.Schema({
username: String,
password: String
});
userSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", userSchema);
如上所述,即使用户已经在数组中,arr.indexOf(user)也会返回-1。为什么会这样?这个问题有更好的解决方案吗?谢谢您的帮助。我一直在敲打这个问题。