I've been digging into this for a while now, found no answer valid and nothing like I want to do on Google so I've come here to ask this question.
How do you populate a Schema like this?
var category_schema = new mongoose.Schema({
name: {required: true, type: String},
parent: {type: Number, ref: 'Category' },
categories: [ {type: Number, ref: 'Category'} ]
});
What I'm doing right now is this:
Category.find({parent: null}).populate({path: 'categories', model: 'Category'}).exec(function(err, categories) {
But doing a console.log on categories would show on the console:
[ { __v: 2,
_id: 18,
name: 'Categoria',
parent: null,
categories:
[ { __v: 1,
_id: 19,
name: 'Children',
parent: 18,
categories: [Object] }, // <= THIS SHOULD HAVE ACTUAL CATEGORIES
{ _id: 20, name: 'Children 2', parent: 18, __v: 0, categories: [] } ] } ]
Any kind of help would be much appreciated.
Thanks.
Edit:
This is what I'm using to show em up
ul.list-group
if inputs == true
li.list-group-item
.radio
label
input(type='radio', class='radio', name='parent_id' value='0')
= 'No category'
mixin make_list(categories, edit)
each category in categories
li.list-group-item
.radio
if inputs == true
input(type='radio', name='parent_id', value='#{category._id}')
= category.name
if categories.length
each category in categories
li.list-group-item
.radio
label
if inputs == true
input(type='radio', name='parent_id', value='#{category._id}')
= category.name
if category.categories.length
ul
+make_list(category.categories, edit)
Since I had no answers, I started digging by myself on how to do this...
Now, this might not be the best way to do it, but oh well;
category_schema.static('make_tree', function(callback) {
Category.find(function(err, categories) {
var parents_array = [];
for(var i = 0; i < categories.length; i++) {
var category = categories[i];
if (category.parent == null || category.categories.length) {
categories[i].categories = [];
parents_array.push(categories[i]);
}
}
for(var x = parents_array.length -1; x >= 0; x--) {
for(var y = 0; y < categories.length; y++) {
if (categories[y].parent === parents_array[x]._id) {
console.log('adding ' + categories[y].name + ' to ' + parents_array[x].name);
parents_array[x].categories.push(categories[y]);
}
}
}
console.log(parents_array);
// Remove parents which have parents.
for(var i = parents_array.length - 1; i >= 0; i--) {
if (parents_array[i].parent) {
parents_array.splice(i, 1);
}
}
callback(parents_array);
});
});
Thing is..., I still get this when I do a console log:
PARENTS ARRAY NOW
[ { __v: 1,
_id: 23,
name: 'Categoria',
parent: null,
categories: [ { parent: 23, name: 'Hijo', _id: 24, __v: 2, categories: [Object] } ] } ]
I think you might be experiencing a vagary of the node console. What happens if you do console.log(categories[0].categories)? (assuming categories is the name of that fisrt object.
Related
MongoDb documents looks like this:
{
"_id": {
"$oid": "60abf5ffc4b1cb61e05bdc48"
},
"club": "FC Midtjylland",
"number": 6,
"__v": 0,
"name": "Joel Andersson"
}
If I create a filter in MongoDB Compass like:
{number: { $in: [6,11] } }
I get all documents with number 6 and 11
In mongose my schema is like:
const Player = new Schema ({
club: { type: String, required: true },
name: { type: String, required: true },
number: { type: Number, required: true },
image: { type: String, required: false },}, { collection: 'players' });
If I try to find the same documents in node.js with mongoose i get no results:
var test = "6,11"
Player.find({number: { $in: [test] }}, function (err, player) {
if (!player || player.length <= 0) {
console.log('No player found!')
ws.send('No player found!');
}
else {
//ws.send(player.number+','+player.name+','+player.image);
console.log(player)
}
})
If I input the numbers directly in the query everything is working fine like:
Player.find({number: { $in: [6,11] }}, funct
What can I do to solve this?
try this:
var test = [6,11]
Player.find({number: { $in: test }}, function (err, player) {
if (!player || player.length <= 0) {
console.log('No player found!')
ws.send('No player found!');
}
else {
//ws.send(player.number+','+player.name+','+player.image);
console.log(player)
}
})
This Code is fetching JSON data from an API service correctly but not updating a nested document in MongoDB, Almost tried everthing
api.squad(matchid, function(datapack) {
var data = JSON.parse(datapack);
for (var i = 0; i < data.squad.length; i++) {
players = data.squad[i].players;
for(var j = 0; j < players.length; j++){
console.log(players[j]); // Working Fine Till here , Data from api showing here in console
var player = { pid: players[j].pid, name: players[j].name };
squadModel.update(
{ leagueId: leagueId },
{$push: {players: player} } // This Update is Not Working
);
}
}
});
The Schema Is As Follows for the code.
// Squad Players -- Sub Schema of Squad
var squadPlayersSchema = mongoose.Schema({
pid:{
type: Number,
required: true
},
name:{
type: String,
required: true
},
type:{
type: String,
},
cost:{
type: Number,
},
country:{
type: String,
},
status : {
type:Boolean,
default:false
}
});
// Squad Schema
var squadSchema = mongoose.Schema({
leagueId:{
type: mongoose.Schema.Types.ObjectId,
ref :'leagueModel',
required: true
},
players : [squadPlayersSchema],
isLaunched : {
type:Boolean,
default:false
}
});
var squads = module.exports = mongoose.model('squads', squadSchema);
Pls help this thing has just refused to work. The update query is just working fine in MongoDB GUI Studio3T Shell
Example Of a demo query run in Studio3T and works fine and updates the document with the code above doesn't.
db.squads.update(
{ "leagueId": ObjectId("5a85900d8b3b30165875ff0d") },
{
"$push": {
"players": { pid: 1234567, name: "Some Name" }
}
}
);
Use $each with $addToSet as follows:
api.squad(leagueId, datapack => {
const data = JSON.parse(datapack);
let updates = []; // array to hold updates promises
data.squad.forEach(squad => { // iterate the data.squad array to get the players list
let promise = squadModel.findOneAndUpdate(
{ leagueId: leagueId },
{ '$addToSet': { 'players': { '$each': squad.players } } },
{ 'upsert': true }
); // update operation as a promise
updates.push(promise);
});
Promise.all(updates).then(console.log).catch(console.error); // resolves when all of the updates promises have resolved
});
I am Facing the error at the time of insert the query.
Error is "db.collection.insert is not a function"
My database schema is like this
'use strict';
var mongoose = require('mongoose');
//Schema
var ABCSchema = mongoose.Schema({
sequenceid: {
type: Number
},
A: {
type: Array,
default: []
},
B: {
type: Array,
default: []
},
C: {
type: Array,
default: []
},
D: {
type: Array,
default: []
}
});
var ABC = module.exports = mongoose.model('ABC', ABCSchema);
Now I want to enter the data which looks like this.
It's just a sample by which you people can understand that how I can Store the value.
{
"_id" : ObjectId("5a2e2eb9104cce1b58385620"),
"sequenceid": 1,
"A" : [
{
"apple" : "red",
"count" : 24
}
],
"B" : [],
"C" : [],
"D" : [],
"__v" : 0
}
Now what I am trying to code is like this
ABC.insert({'sequenceid': 1, 'A': {'apple': 'red', 'count': 24}}, function(error, data){
console.log(data);
});
As #Manjeet Thakur pointed out what you are trying to insert at "A" is and object and not an Array
Change it to array
{
"A": [{
"apple": "red",
"count": 24
}],
"sequenceid": 1
}
Also you need to instantiate your model and save it
var abc = new ABC({'sequenceid': 1, 'A': [{'apple': 'red', 'count': 24}]});
abc.save()
//or
ABC.create({'sequenceid': 1, 'A': [{'apple': 'red', 'count': 24}]}, function (err, small) {
//if (err) return throw err;
// saved!
})
'use strict';
var mongoose = require('mongoose');
//Schema
var ABCSchema = mongoose.Schema({
sequenceid: {
type: Number
},
A: {
type: Array,
default: []
},
B: {
type: Array,
default: []
},
C: {
type: Array,
default: []
},
D: {
type: Array,
default: []
}
});
var ABC = module.exports = mongoose.model('ABC', ABCSchema);
// here now collection is ABC (name of collection)
ABC.insert({'sequenceid': 1, 'A': [{'apple': 'red', 'count': 24}] }, function(error, data){
console.log(data);
});
I am making a barcode scanner for my school project but i am stuck. I dont know how to scan through this object. I have this object with objects inside, and I need to scan through each object inside storage variable to check its barcode.
var storage = {
bolts: {
barcode: 57263144,
price: 0.5,
name: 'Plain Brackets',
stock: 25,
},
brackets: {
barcode: 13245627,
price: 0.2,
name: '100mm Bolts',
stock: 2,
},
}
I have a variable called barcode, and I need to test this variable if its the same like one of these. I tried using
for (var key in storage){
if (storage[key].barcode === barcode){
}
}
I would like the most simple way to do that.
Use Object.keys:
Object.keys(obj).forEach(function(key) {
console.log(key, obj[key]);
});
Below is the example:
var storage = {
"bolts": {
barcode: 57263144,
price: 0.5,
name: 'Plain Brackets',
stock: 25,
},
"brackets": {
barcode: 13245627,
price: 0.2,
name: '100mm Bolts',
stock: 2,
}
}
var barcode = 57263144;
Object.keys(storage).forEach(function(key) {
if(storage[key].barcode === barcode) { console.log("do something")}
});
A Fiddle:
https://jsfiddle.net/spechackers/34bhthza/
Use the recursive function to verify if exist more nodes in the objects, example:
const complexObj = {
name: "nobody",
address: { number: 22, moreNumbers: [1,2,3,4,5] },
colors: ["green", "red"],
numbersAgain: { first: 1, second: 4 }
};
function scanObj(obj){
for (let i in obj) {
/*
*Do some verificatio, example:
*I'd like to verify all numbers and if the numbers is greater than 3:
*/
if(typeof obj[i] == "number" && obj[i] > 3){ console.log(obj[i]); }
if (typeof obj[i] === "object") {
scanObj(obj[i])
}
}
}
//call the method
scanObj(complexObj);
Output: 22 4 5 4
Engine Collection
var EngineSchema = new mongoose.Schema({
name: String,
GF2: String,
GF3: String,
GF4: String,
ll98: String,
ll01: String,
ll04: String
});
Oil Collection
var OilSchema = new mongoose.Schema({
name: String,
GF2: String,
GF3: String,
GF4: String,
ll98: String,
ll01: String,
ll04: String
});
I made simple
Engine DB
{ _id: 57d9604b7ecbc0029a3aad3c,
name: 'N54 B30A',
ll01: '1',
ll01fe: '1',
ll04: '1',
__v: 0 }
OilDB
[ { _id: 57d9614265e6c402a2c09990, name: 'EDGE', ll04: '1', __v: 0 },
{ _id: 57d98e12acc05505cfd15aae,
name: 'SYNTEC',
GF2: '1',
GF3: '1',
GF4: '1',
__v: 0 } ]
If I have the N54 B30A than It needs classification about ll98, ll01, ll04
EDGE Product only one about classification ll04
totally I choose the 'N54 B30A' that has ll04 classification so I want to appear something that has the ll04 classification
'N54 B30A' -> ll04
'EDGE' -> ll04
ll04 mapping?
Select N54 B30A -> appear EDGE
My Code Simple but It did't execute
Engine.findOne({name: 'N54 B30A'}, {_id: 0, name: 0, __v: 0}, function(err, engine) {
var result = Object.keys(engine.toObject());//[ 'll01', 'll01fe', 'll04' ]
Oil.findOne({result[2] : 1},function (err, oil) {
console.log(oil)
});
})
More Question
I want to search many kind atrribute(ll01, ll01fe, ll04) such as
findOne({$or:{ll01:1},{ll01le:1},{ll04:1}},function...)
but I don't know how to add one item like {ll01 : 1} than add {ll01le:1} and {ll04:1}
I tried coding
My Code
Engine.findOne({name: 'N54 B30A'}, {_id: 0, name: 0, __v: 0}, function (err, engine) {
var result = Object.keys(engine.toObject());//[ 'll01', 'll01fe', 'll04' ]
var Json = [];
result.forEach(function (item) {
var code = {};
code[item] =1;
Json.push(code);
});
console.log(Json);
Oil.find({$or: Json}, function (err, oil) {
console.log(oil)
});
})
I'm not useful javascript so I made by only my thinking. is this right?
You cannot assign a value to JSON as {result[2] : 1}. Change your code to this
Engine.findOne({name: 'N54 B30A'}, {_id: 0, name: 0, __v: 0}, function(err, engine) {
var result = Object.keys(engine.toObject());//[ 'll01', 'll01fe', 'll04' ]
var oilFindQuery = {};
oilFindQuery[result[2]] = 1;
//or query
var orQuery = [];
result.forEach(function (item) {
var queryItem = {};
queryItem[item] = 1
orQuery.push(queryItem);
});
//oilFindQuery = {$or: orQuery};
Oil.findOne(oilFindQuery, function (err, oil) {
console.log(oil)
});
})