user1874773 user1874773 - 2 months ago 22
Node.js Question

Update or add new object into array in mongoose nodejs

I am new to node Js so I am having difficulties to update (insert) a new object to
array.

Here is the schema :

var Schema = new mongoose.Schema({
name: String,
ips: [{
ip: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Ip'
}
}]
});


I am trying to add new row into ips array like so :

IP schema :

var IpSchema = new mongoose.Schema({
ip: String,
objects: [{
object:{
type: mongoose.Schema.Types.ObjectId,
ref: 'object'
}
}]
});

var tmpIp = new Ip({
ip: "5.5.5.5",
objects:
[{object:obj._id}]
});

tmpIp.save();

DB.update({name: 'xxxx'},{$push: {ips:{tmpIp}}},{upsert:true},function(err){
if(err){
console.log(err);
}else{
console.log("Successfully added");
}
});


On execute only
_id
is created (example the 3 row ). In addition to this the created id isn't related to any real
ip
on IPS table.

"ips" : [
{
"ip" : ObjectId("57d12ddf16a6f6fc175fbfb5"),
"_id" : ObjectId("57d12ddf16a6f6fc175fbfbc")
},
{
"ip" : ObjectId("57d12ddf16a6f6fc175fbfb7"),
"_id" : ObjectId("57d12ddf16a6f6fc175fbfbb")
},
{
"_id" : ObjectId("57d12defd5cc02b810601bb4")
}
]


The result that I am trying to reach is like the first 2 rows:
ip
- the object id of the created IP object
_id
and not only
_id

Answer

Thanks all

The only thing missing was to add the ip (for some reason i didn't ) please see the bold text.

PhishingDB.update({url: urlReq},{$push: {ips:{**ip**:tmpIp}}},{upsert:true},function(err){ if(err){ console.log(err); }else{ console.log("Successfully added"); } });

Comments