I'm getting an error
TypeError: Cannot read property 'tasks' of undefined
When I try a new POST request on my api, following is the request body I'm trying to make
{
"name": "tecnica1",
"description": "tecnica ensino1",
"rules": ["Regra1", "Regra2"],
"delivery_mode": ["Face to face", "Blended"],
"interaction": ["Group based", "One to many"],
"interrelationship": "High",
"motivation": "High",
"participation": ["Medium", "Low"],
"performance": ["Low", "None"],
"scope": ["Open ended", "Close ended"],
"feedback_use": "Low",
"target_audience": [15, 17],
"learning_objectives" : [
{
"knowledge_category": "Factual",
"behaviour": "Comparing",
"subject_matter": "teste",
"conditions": "teste",
"degree": "teste"
},
{
"knowledge_category": "Procedural",
"behaviour": "Explaining",
"subject_matter": "teste"
}
],
"affective_objectives": "teste",
"social_objectives": "teste",
"structure": {
"modules": [{
"name": "teste",
"phases": [{
"name": "teste",
"tasks": [{
"type": "tipo1",
"description": "teste",
"role": "Student",
"resources": ["Recurso1", "Recurso2"]
}]
},
{
"name": "test2",
"tasks": [{
"type": "tipo1",
"description": "teste",
"role": "Student",
"resources": ["Recurso1", "Recurso2"]
},
{
"type": "tipo1",
"description": "teste",
"role": "Student",
"resources": ["Recurso1", "Recurso2"]
}]
}]
}]
}
}
The error refers to the nested objects "Tasks", under Structure/Modules/Phases
Here's the model describing the object I'm trying to post and the controller function handling that.
Tecnica.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const idValidator = require('mongoose-id-validator');
const EVAL = ['High', 'Medium', 'Low', 'None']
let TaskSchema = new Schema({
type : {
type : String,
required : true
},
description : {
type : String,
required : true
},
role : {
type : String,
required : true,
enum : ['Student', 'Staff']
},
resources : [String]
});
let PhaseSchema = new Schema({
name : {
type : String,
required : true
},
tasks : {
type : [TaskSchema],
validate : {
validator: function(v){
return v.length >= 1;
},
message : 'At least one task should be defined.'
}
}
});
let ModuleSchema = new Schema({
name : {
type : String,
required : true
},
phases : {
type : [PhaseSchema],
validate : {
validator: function(v){
return v.length >= 1;
},
message : 'At least one phase should be defined.'
}
}
});
let EstruturaTecnicaSchema = new Schema({
modules : {
type : [ModuleSchema],
validate : {
validator: function(v){
return v.length >= 1;
},
message : 'At least one module should be defined.'
}
}
});
let LearningSchema = new Schema({
knowledge_category : {
type : String,
required : true,
enum : ['Factual', 'Conceptual', 'Procedural', 'Metacognitive']
},
behaviour : {
type : String,
required : true
},
subject_matter : {
type : String,
required : true
},
// Optinal/if any
conditions : String,
degree : String
});
/*
Technique defined by:
Init Data + Tlt Data.
Init Data consists of name, description and set of rules.
Tlt Data is defined by context and structure
*/
let TecnicaSchema = new Schema({
//Init Data
name : {
type : String,
required : true
},
description : {
type : String,
required : true
},
rules : [String],
//Context
delivery_mode : {
type : [String],
required : true
},
interaction : {
type : [String],
required : true
},
// Perception
// interrelationship, motivation, participation, performance
interrelationship : {
type : [String],
required : true,
enum : EVAL
},
motivation : {
type : [String],
required : true,
enum : EVAL
},
participation : {
type : [String],
required : true,
enum : EVAL
},
performance : {
type : [String],
required : true,
enum : EVAL
},
scope : {
type : [String],
required : true
},
feedback_use : {
type : [String],
required : true,
enum : EVAL
},
target_audience : {
type : [Number],
required : true
},
learning_objectives : {
type : [LearningSchema],
validate : {
validator: function(v){
return v.length >= 1;
},
message : 'At least one learning objective should be defined.'
}
},
affective_objectives : {
type : [String]
},
social_objectives : {
type : [String]
},
structure : {
type : EstruturaTecnicaSchema,
required : true
},
psychologist : {
type : mongoose.Schema.Types.ObjectId,
ref : 'User',
required : true
}
});
TecnicaSchema.plugin(idValidator);
module.exports = mongoose.model('Tecnica', TecnicaSchema);
tecnicas.controller.js
function create(req, res) {
let tecnica = new Tecnica();
let learning_objectives = req.body.learning_objectives;
let structure = req.body.structure;
let modules = req.body.structure.modules;
let phases = req.body.structure.modules.phases
let tasks = req.body.structure.modules.phases.tasks;
phases.tasks = tasks.map(t => { return t; });
modules.phases = phases.map(p => { return p; });
structure.modules = modules.map(m => { return m; });
tecnica.name = req.body.name;
tecnica.description = req.body.description;
tecnica.rules = req.body.rules;
tecnica.delivery_mode = req.body.delivery_mode;
tecnica.interaction = req.body.interaction;
tecnica.interrelationship = req.body.interrelationship;
tecnica.motivation = req.body.motivation;
tecnica.participation = req.body.participation;
tecnica.performance = req.body.performance;
tecnica.scope = req.body.scope;
tecnica.feedback_use = req.body.feedback_use;
tecnica.target_audience = req.body.target_audience;
tecnica.learning_objectives = learning_objectives.map(l => {
return l;
});
tecnica.affective_objectives = req.body.affective_objectives;
tecnica.social_objectives = req.body.social_objectives;
tecnica.structure = req.body.structure;
tecnica.psychologist = req.user;
tecnica.save()
.then(t => {
return res.status(201).json(t);
})
.catch(utils.handleError(req, res));
}
How can I parse the tasks?
I'm already using body-parser with the options
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
modules, phases, tasks are Arrays. You can't call
req.body.structure.modules.phases.tasks
req.body.structure.modules is an array
req.body.structure.modules.phases doesn't exist and is undefined.
A better way to assign properties like this:
function create(req, res) {
let tecnica = new Tecnica();
Object.assign(tecnica, { ...req.body });
tecnica.psychologist = req.user;
tecnica.save()
.then(t => {
return res.status(201).json(t);
})
.catch(utils.handleError(req, res));
}
Related
I have created a user which has its login data and into it is has some arrays including friends, groups, pages and other stuff.
But I am stucked when I want see who has sent me a friend request.
So I have am trying to create the friend request/response as in Facebook.
My logic it is for the moment when I send you a friend request I add to my array of friends and then with post request I can see at which users is my ID added and it has the status Pending.
For the moment I have tried something but I am getting empty array as response.
My code is below.
User model
const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const userDataScheme = new mongoose.Schema({
firstName: String,
lastName: String,
email: {
type: String,
unique: true
},
password: String,
phone: {
number: String,
countryCode: String,
dialCode: String,
e164Number: String,
internationalNumber: String,
nationalNumber: String
},
gender: Number,
birthday_day: String,
birthday_month: String,
birthday_year: String,
friends: [{
_id: false,
friendId: String,
createdDate: { type: Date, default: Date.now },
status: Number,
}
]
},
{ autoIndex: false });
userDataScheme.plugin(uniqueValidator, { message: 'Email already in use.' });
module.exports = mongoose.model('User', userDataScheme);
user.service.js backend
const User = require("../models/user");
async function findYourPendingContact({friendId}) {
return await User.find({friends: friendId});
}
module.exports = {
findYourPendingContact
}
routes.js
routes.post("/user-friends", UserController.findYourContacts);
This is the Controller.
const userService = require("../service/user.service");
async findYourContacts(req, res, next) {
let friendId = req.body.friendId;
userService.findYourPendingContact({friendId: friendId})
.then(friends => res.json(friends))
.catch(err => next(err));
}
So seems my Database Json.
The user that added me as friend.
{
"_id" : ObjectId("620bfd2d860fd314fc538df3"),
"firstName" : "Max",
"email" : "maxmuster#outlook.de",
"lastName" : "Muster",
"password" : "$2b$10$D8l15CTZHbp/rcApqXpwT.KUbHAg0hBYp0h1qounnKFW.plDO9wKe",
"phone" : {
"number" : "1234566",
"countryCode" : "DE",
"dialCode" : "+49",
"e164Number" : "+491234566",
"internationalNumber" : "+49 1234566",
"nationalNumber" : "1234566"
},
"gender" : 1,
"birthday_day" : "13",
"birthday_month" : "8",
"birthday_year" : "1998",
"friends" : [
{
"friendId" : "6204605617d5fcc3c179f3cc", // this here is my ID
"status" : 0,
"createdDate" : {
"$date" : 1644971031461
}
}
],
"__v" : 0
}
Here are my Data on backend
{
"_id" : ObjectId("6204605617d5fcc3c179f3cc"),
"firstName" : "Test",
"email" : "test.test#outlook.com",
"lastName" : "Test",
"password" : "$2b$10$koGb0fIcdWvq2ugGQXF7.OOmoof1QCH8IKQtoMGl9MHSJuu5Xumd6",
"phone" : {
"number" : "01234567",
"countryCode" : "DE",
"dialCode" : "+49",
"e164Number" : "+4901234567",
"internationalNumber" : "+49 01234567",
"nationalNumber" : "01234567"
},
"gender" : 0,
"birthday_day" : "8",
"birthday_month" : "5",
"birthday_year" : "1994",
"__v" : 0
}
Now this is the part of my frontend when I login.
public getUserFriends(userId): Observable<any> {
const api = `${this.baseUrl}/user-friends`
return this.http.post(api, JSON.stringify({friendId: userId}), this.httpOptions).pipe(
map((response: User) => {
console.log(response);
return response;
},
(err) => {
throw err;
})
)
}
user.helper.ts
showPendingFriends(authId): Observable<any> {
return new Observable<any>(observer => {
this.userService.getUserFriends({friendId: authId}).subscribe(response => {
observer.next(response);
})
})
}
components.ts
this.userHelper.showPendingFriends(this.authService.userID).subscribe(res => console.log(res)); //this.authService.userID is my ID actually 6204605617d5fcc3c179f3cc or it can be any user ID
i want to build a cart for my website, this is the schema for the cart:
const productSchema = require("./product")[1];
const cartItemSchema = new Schema<CartItem>(
{
product: productSchema,
quantity: {
type: Number,
required: true,
min: [1, "Quantity can not be less then 1."],
},
},
{
timestamps: true,
}
);
const CartSchema = new Schema(
{
userID: {
type: Schema.Types.ObjectId,
ref: "User",
},
items: [cartItemSchema],
},
{ timestamps: true }
);
module.exports = model<Cart>("Cart", CartSchema);
the problem is, when I add a product in a specific user cart, while the same product is allready added to another user cart document, I get this error:
"message":"cannot add to cart E11000 duplicate key error collection: elec-store.carts index: items.productID_1 dup key: { items.productID: null }, stack: MongoError: E11000 duplicate key error collection: elec-store.carts index: items.productID_1 dup key
this is the add function
public async add(cartItem: CartItem, userID: string): Promise<Cart> {
let cartInDB = null;
await CartModel.findOne({ userID: userID }, (err, cart) => {
cartInDB = cart;
});
if (AppUtils.hasValue(cartInDB)) {
const index = cartInDB.items.findIndex(
(item) => item.product._id.toString() === cartItem.product._id
);
if (index !== -1) {
cartInDB.items[index].quantity =
cartInDB.items[index].quantity + cartItem.quantity;
cartInDB.items[index].product._id = cartItem.product._id;
const cartAfterAdding = await cartInDB.save();
return cartAfterAdding;
} else {
await CartModel.update(
{ _id: cartInDB._id },
{ $push: { items: cartItem } }
);
}
return cartInDB;
} else {
const itemsArray: CartItem[] = [];
itemsArray.push(cartItem);
let createdCart = new CartModel({
userID: userID,
items: itemsArray,
});
await createdCart.save(); \\ this is where the problem occurs
return createdCart;
}
}
and this is how my cart looks like in mongodb document:
db.carts.find().pretty()
{
"_id" : ObjectId("60ea9fb81b2b4c048c3b1544"),
"userID" : ObjectId("60dee5e1da81bd274cd304de"),
"items" : [
{
"_id" : ObjectId("60ea9fb81b2b4c048c3b1545"),
"product" : {
"_id" : ObjectId("60e62cb21f74572b7c0b3a30"),
"name" : "tv",
"description" : "the best tv",
"categoryID" : 2,
"quantity" : "2",
"serialNumber" : "226swaq12",
"price" : 2000,
"imgUrl" : "https://www.seekpng.com/png/full/774-7744281_samsung-electronics-samsung-electronic-product-png.png"
},
"quantity" : 6,
"createdAt" : ISODate("2021-07-11T07:37:29.790Z"),
"updatedAt" : ISODate("2021-07-11T07:38:15.583Z")
},
{
"_id" : ObjectId("60eaa16b1b2b4c048c3b155d"),
"product" : {
"_id" : ObjectId("60e066009be1060748201ad3"),
"name" : "samsung tv",
"description" : "the best tv",
"quantity" : "2",
"categoryID" : 2,
"serialNumber" : "2212",
"price" : 2000,
"imgUrl" : "https://www.seekpng.com/png/full/774-7744281_samsung-electronics-samsung-electronic-product-png.png"
},
"quantity" : 9,
"updatedAt" : ISODate("2021-07-11T07:46:19.313Z"),
"createdAt" : ISODate("2021-07-11T07:44:43.764Z")
}
],
"createdAt" : ISODate("2021-07-11T07:37:29.792Z"),
"updatedAt" : ISODate("2021-07-11T07:46:19.314Z"),
"__v" : 0
}
I use mongoose.Schema to create new schemas and then when making reference to a different schema I do it like this:
product: { type: mongoose.Schema.Types.ObjectId, ref: 'product' },
If later you need to show also the product info (db.carts.find()), you can use populate() to replace the reference for all the product entries.
You can use upsert true.
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ],
hint: <document|string> // Available starting in MongoDB 4.2
}
)
For example -
db.books.update(
{ item: "ZZZ135" }, // Query parameter
{ // Replacement document
item: "ZZZ135",
stock: 5,
tags: [ "database" ]
},
{ upsert: true } // Options
)
This may help: Mongo Update
Basically I have the following schema.
{
...,
description: {
type: String,
required: true,
trim: true
},
tags: {
type: [{
type: String
}]
},
lessons: [{
name: String,
description: String,
video_path: String,
comments: [
{
user: mongoose.Schema.ObjectId,
content: String,
createdAt: {
type: Date,
default: Date.now
}
}
]
}]
,
createdAt: {
type: Date
}
}
I want to insert the following object to the comments array of a lesson object when the id of the lesson object is given.
{
userId: "5e1b4790f7a3ca42accfeed3",
content: "First comment"
}
The following is what I have tried. However it doesn't throw any error, but it's not inserting any comments to the DB also. Thanks for any helpful advice.
addComment: async (courseId, lessonId, userId, content, callback) => {
Course.update(
{ _id: courseId, "lessons._id": lessonId },
{
$push: {
comments: {
user: userId,
content: content
}
}
},
function(err, data) {
if (err) {
console.log(err);
return callback(err, null);
} else {
console.log(data);
return callback(null, data);
}
}
);
}
EDIT:
Collection data:
{
"_id" : ObjectId("5e1b4790f7a3ca42accfeed3"),
"tags" : [ "mathematics", "beginner", "fundamentals" ],
"name" : "Mathematics Toobox",
"description" : "Mathematics includes the study of such topics as quantity (number theory), structure (algebra), space (geometry), and change (mathematical analysis).",
"price" : 1500,
"lessons" : [
{
"_id" : ObjectId("5e1b48d9f7a3ca42accfeed4"),
"name" : "Welcome to the course",
"description" : "Welcome to Mathematics Toolbox course\n I’ll be your instructor for this course that runs for xx weeks ending on XXXXX.\n1. Access the technology tutorial located on your My Home page if you are new to the learning Hub, this online learning management system.",
"video_path" : "uploads\\1578846427336-Shakira - Hips Don't Lie ft. Wyclef Jean.mp4"
},
{
"_id" : ObjectId("5e1e8f80cf166a2cb82b7a5e"),
"name" : "Number system",
"description" : "Baby just love me love me love me\nBaby just hold me hold me hold me\nOh love me ",
"video_path" : "uploads\\1579061121969-Ellis - Migraine (feat. Anna Yvette) [NCS Release].mp4"
}
],
"createdAt" : ISODate("2020-01-12T16:21:36.778Z"),
"__v" : 0,
"cover_path" : "uploads\\1578846099107-img_4.jpg"
}
There are a few problems in your schema.
I think you want to have an array of string tags.
Also you need to use ref property to make a reference to the User model.
So schema must be updated like this:
(I assume that you used User in model creation.)
const mongoose = require("mongoose");
const courseSchema = new mongoose.Schema({
description: {
type: String,
required: true,
trim: true
},
tags: {
type: [String]
},
lessons: [
{
name: String,
description: String,
video_path: String,
comments: [
{
user: {
type: mongoose.Schema.ObjectId,
ref: "User"
},
content: String,
createdAt: {
type: Date,
default: Date.now
}
}
]
}
],
createdAt: {
type: Date
}
});
module.exports = mongoose.model("Course", courseSchema);
Now you can use findByIdAndUpdate method with push and filtered positional operator $.
to add a comment like this:
Course.findByIdAndUpdate(
{ _id: courseId },
{
$push: { "lessons.$[lesson].comments": { user: userId, content } }
},
{
arrayFilters: [{ "lesson._id": lessonId }],
new: true
},
function(err, data) {
if (err) {
console.log(err);
return callback(err, null);
} else {
console.log(data);
return callback(null, data);
}
}
);
Test:
Let's say you have an user with _id: 5e20954dc6e29d1b182761c9, and a course like this:
{
"tags": [
"tag1",
"tag2"
],
"_id": "5e209631a90e651e9c238df2",
"description": "description1",
"lessons": [
{
"comments": [],
"_id": "5e209631a90e651e9c238df3",
"name": "lesson1 name",
"description": "lesson1 description",
"video_path": "lesson1 video_path"
}
],
}
When you send a comment with these values:
courseId = "5e209631a90e651e9c238df2",
lessonId = "5e209631a90e651e9c238df3",
userId = "5e20954dc6e29d1b182761c9",
content = "Comment Content"
The result will be:
{
"_id" : ObjectId("5e209631a90e651e9c238df2"),
"tags" : [
"tag1",
"tag2"
],
"description" : "description1",
"lessons" : [
{
"comments" : [
{
"_id" : ObjectId("5e2099799edf132a08c2b997"),
"user" : ObjectId("5e20954dc6e29d1b182761c9"),
"content" : "Comment Content",
"createdAt" : ISODate("2020-01-16T20:12:25.243+03:00")
}
],
"_id" : ObjectId("5e209631a90e651e9c238df3"),
"name" : "lesson1 name",
"description" : "lesson1 description",
"video_path" : "lesson1 video_path"
}
]
}
This is what finally worked for me.
const newData = {
'lessons.$.comments': {
user: userId,
content: content
}
}
Course.updateOne({_id: courseId,'lessons._id': lessonId}, {'$push':
newData
}, function(err,num) {
console.log(num)
if(num.nModified > 0){
callback(null,num)
}
else if(err){
callback(err,null)
}
})
}
I have a mongoose schema for categories
import mongoose from 'mongoose';
import { imageScheme } from './data.schemas';
mongoose.plugin(require('mongoose-delete'));
mongoose.plugin(require('mongoose-timestamp'));
const Schema = mongoose.Schema;
const catScheme = new Schema({
title: {
type: String
},
subTitle: {
type: String
},
description: {
type: String
},
images: [imageScheme],
icon: {
type: String
},
deleteAt: {
type: Date,
default: null
}
});
const Category = mongoose.model('Category',catScheme);
export default Category;
my image schema is located in another file
const imageScheme = new Schema({
imageCaption : {
type: String
},
imageFileName: {
type: String,
required: true
},
imagePath: {
type: String,
required: true
}
});
and when I am using the model for creating new category its adding the timestamp and deleted for my images array which means its loading the plugins ( mongoose-delete , mongoose-timestamp ) into the sub schema
HOW TO AVOID THAT ?
that is the result
{
"_id" : ObjectId("5d5a822f20179023e008f10c"),
"deleteAt" : null,
"deleted" : false,
"title" : "Eyes and Ears",
"description" : "here you will find all ppe to keep your eye 6 sharp",
"icon" : "glass.svg",
"images" : [
{
"_id" : ObjectId("5d5a822f20179023e008f10e"),
"deleted" : false,
"imageCaption" : "Eyes and Ears",
"imageFileName" : "67acca17-3fc8-416c-bc00-8273770b2115.jpeg",
"imagePath" : "resources/images/67acca17-3fc8-416c-bc00-8273770b2115.jpeg",
"updatedAt" : ISODate("2019-08-19T11:04:15.756Z"),
"createdAt" : ISODate("2019-08-19T11:04:15.756Z")
},
{
"_id" : ObjectId("5d5a822f20179023e008f10d"),
"deleted" : false,
"imageCaption" : "Eyes and Ears",
"imageFileName" : "9f1c5b1f-c1be-48f2-a9bc-8294930fd4c9.jpeg",
"imagePath" : "resources/images/9f1c5b1f-c1be-48f2-a9bc-8294930fd4c9.jpeg",
"updatedAt" : ISODate("2019-08-19T11:04:15.756Z"),
"createdAt" : ISODate("2019-08-19T11:04:15.756Z")
}
],
"updatedAt" : ISODate("2019-08-19T11:04:15.756Z"),
"createdAt" : ISODate("2019-08-19T11:04:15.756Z"),
"__v" : 0
}
It looks like you are plugging the mongoose-delete and mongoose-timestamp in the whole database.
Have you tried the example provided in the plugin pages?
catScheme.plugin(mongoose-timestamp)
catScheme.plugin(mongoose-delete)
I have a Team Schema holding details about teams, and a Match Schema to store these teams in. I am trying to make it so that the home/away teams in the Match Schema are references to the Team object. I have put my code below, I'm getting an error when saving the Team but I can't help but feel I have done something wrong with the Schema's or the saving of the Match. Can anyone help?
So far I have the following code:
Team.js extract
var Team = new Schema({
'key' : {
unique : true,
type : Number,
default: getId
},
'name' : { type : String,
validate : [validatePresenceOf, 'Team name is required'],
index : { unique : true }
}
});
module.exports.Schema = Team;
module.exports.Model = mongoose.model('Team', Team);
Match.js extract
var util = require('util');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Team = require('../schemas/Team').Schema;
var Match = new Schema({
'key' : {
unique : true,
type : Number,
default: getId
},
'hometeam' : {
type : Schema.ObjectId,
ref : 'Team'
},
'awayteam' : {
type : Schema.ObjectId,
ref : 'Team'
}
});
module.exports = mongoose.model('Match', Match);
index.js
app.get('/match', function(req, res) {
var key = 1356136550152; // Reading
Team.findByKey(key, function(err, team) {
if(err) {
res.send("An error occured");
}
if(!team) {
res.send("The team does not exist");
}
var match = new Match();
match.hometeam = team;
match.save(function(err) {
if(err) {
util.log('Error while saving Match: ' + util.inspect(err));
res.send("An error occured whilst saving the match");
} else {
res.send("Saved the match");
}
});
});
});
ERROR:
Error while saving Match: { message: 'Cast to ObjectId failed for value "{ name: \'testTeam\',\n _id: 50d500663ca6067226000001,\n __v: 0,\n key: 1356136550152 }" at path "hometeam"',
name: 'CastError',
type: 'ObjectId',
value:
[ { name: 'testTeam',
_id: 50d500663ca6067226000001,
__v: 0,
key: 1356136550152 } ],
path: 'hometeam' }
Error with team._id
Error while saving Match: { [MongoError: E11000 duplicate key error index: testdb.matches.$team.name_1 dup key: { : null }]
name: 'MongoError',
err: 'E11000 duplicate key error index: testdb.matches.$team.name_1 dup key: { : null }',
code: 11000,
n: 0,
connectionId: 8,
ok: 1 }
db.matches.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"ns" : "testdb.matches",
"name" : "_id_"
},
{
"v" : 1,
"key" : {
"key" : 1
},
"unique" : true,
"ns" : "testdb.matches",
"name" : "key_1",
"background" : true,
"safe" : null
},
{
"v" : 1,
"key" : {
"team.key" : 1
},
"unique" : true,
"ns" : "testdb.matches",
"name" : "team.key_1",
"background" : true,
"safe" : null
}
]
In index.js it should be:
match.hometeam = team._id;
instead of:
match.hometeam = team;
UPDATE
Regarding the new error message, it looks like you have a unique index on the matches collection that refers to fields that don't exist. Drop it in the shell using:
db.matches.dropIndex('team.name_1')