Mongodb - How to insert an Objectid via variable?

Asked

Viewed 164 times

2

I’m learning MongoDB and a problem came up, I’m trying to insert an Objectid into an array via variable, but I’m not getting it. I’m doing it this way:

> var aluno = db.alunos.find({"nome" : "leandro"});
> aluno;
{ "_id" : ObjectId("5ada02cc6c0218c2b64e0214"), "nome" : "leandro", "data_nasc" : ISODate("1996-07-19T03:00:00Z") }

Now at the time when I try to insert only the "_id" field occurs the following:

> db.professores.update({"nome" : "leandro"}, {$push : {"alunos" : aluno["_id"]}}) 
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.professores.find({ })
{ "_id" : ObjectId("5ad55f59f034bcd625334947"), "nome" : "leandro", "curso" : "guitarra", "alunos" : [ undefined ] }

The entered value is "Undefined". What I’m doing wrong?

1 answer

-1

Model Alunos = {
nome:String,
data_nasc:Date}

Model Professores = {
nome: String,
curso: String,
alunos[{
 id:{
 type: Schema.Type.ObjectId
 ref:'Alunos'
}
}]

you can pass an array of objects

then on Function and like this

var aluno= {
 "nome":[{
 "id":"afafg1321faqf"
}]
}

db.Professores.findOneAndUpdate({nome:"Leandro"},{$Push:{alunos:alunos}})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.