tournament.js
var mongoose = require('mongoose');
var TournamentPlayer = require('../models/tournamentPlayer');
var SportPlayer = require('../models/sportPlayer');
var Schema = mongoose.Schema;
var TournamentSchema = new Schema({
tournamentPlayers:[{
type: Schema.Types.Mixed,
ref: 'TournamentPlayer'
}],
buyin: Number,
entrants: Number,
prizePool: Number,
name: String,
sport: String,
endOfRegistration:Date,
sportsPlayers:[{
type: Schema.Types.Mixed,
ref: 'SportPlayer'
}],
created: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('Tournament', TournamentSchema);
api.js
tournament.tournamentPlayers[player.userId]=player;
console.log("ass array"+util.inspect(tournament.tournamentPlayers,false,null));
console.log("ass array element" + util.inspect(tournament.tournamentPlayers[player.userId] ,false,null));
console.log("ass array just in case"+util.inspect(tournament.tournamentPlayers,false,null));
tournament.tournamentPlayers.push(player);
console.log("push"+util.inspect(tournament.tournamentPlayers,false,null));
输出
ass array[]
ass array element{ username: 'batman',
roster:
{ __v: 0,
userId: '57bb89eb10c4b4ac124980b9',
tournamentId: '57d49f5169cc78ac21c5e791',
_id: '57d4b421315f1b501ad5456f',
playerRoster:
[ { _id: '57cfe922dcba0f295f57e26d', playerFirstName: 'Julio' },
{ _id: '57cfe939dcba0f295f57e274', playerFirstName: 'Odell' } ] },
rank: 'blah',
totalPoints: 0,
userId: '57bb89eb10c4b4ac124980b9',
_id: '57d4b421315f1b501ad54570' }
ass array just in case[]
push[{"username":"batman","roster":{"__v":0,"userId":"57bb89eb10c4b4ac124980b9","tournamentId":"57d49f5169cc78ac21c5e791","_id":"57d4b421315f1b501ad5456f","playerRoster":[{"_id":"57cfe922dcba0f295f57e26d","playerFirstName":"Julio"},{"_id":"57cfe939dcba0f295f57e274","playerFirstName":"Odell"}]},"rank":"blah","totalPoints":0,"userId":"57bb89eb10c4b4ac124980b9","_id":"57d4b421315f1b501ad54570"}]
我正在尝试声明并将对象添加到关联数组中。当我查找它们时,我想使用userId而不是_id。尝试使用此代码时,可以直接调用对象tournamentPlayers [userId],但不会将其显示为数组tournamentPlayers的一部分。当我进行常规推送时,会显示,但这不是我想要的。我可以使用该对象,但不能通过mongoose保存它。
我见过几个问题,但他们没有回答这个问题。这里的第二个答案有严格:false作为设置,但不适用于单个架构元素。 Mongoose: Saving as associative array of subdocuments vs array of subdocuments
如何在mongoose中向对象数组声明和添加对象?