janez89 / mongoose-materialized Goto Github PK
View Code? Open in Web Editor NEWmongoose materialized plugin
mongoose materialized plugin
For the static GetChildren method, there's no check if the doc is there (https://github.com/janez89/mongoose-materialized/blob/master/lib/materialized.js#L572). This throws an exception if no document was found.
I see it in the document but I don't know how to use it?
Thanks.
Hello, I was wondering if it is somehow possible to get a tree with a bit of a different structure.
Currently when I call GetTree on a document I get something like this back:
{
"53ed04d4e0254ec41e4ad40e":{
"_id":"53ed04d4e0254ec41e4ad40e",
"path":"",
........
"children":{
"53ed04fbdff632fc1b5a4e1e":{
"_id":"53ed04fbdff632fc1b5a4e1e",
"path":",53ed04d4e0254ec41e4ad40e",
"parentId":"53ed04d4e0254ec41e4ad40e",
........
},
"53ed04e6dff632fc1b5a4e1b":{ ..........
(removed some key/values so it isn't to big)
I was wondering if it was possible to get it returned like this:
[
{
"_id": "53ed04d4e0254ec41e4ad40e",
"path": ,
"children": [
{
"_id": "53ed04fbdff632fc1b5a4e1e",
"path": ",53ed04d4e0254ec41e4ad40e",
"children": []
}
]
}
]
So basically all the documents are wrapped in a array so they are easy approachable, this way it is easier to navigate through a document its children when you return it as a tree. This notation is also the most supported notation for a lot of different modules/plugins. So it would be awesome if we can get this as a result so we can directly feed it to other modules.
It seems like skip/limit for getDescendants doesn't work. Any idea if this is something that could be added in or is there another method that will give this functionality? Thanks!
Is there anyway to maintain a condition for this method?
Hello,
When using Cat.AppendChild(parentId, Doc)
. This works to update the direct relationship between Doc and the parentId, however if Doc has children, those children seem to get lost. Their path isn't updated.
Is there a better way for 'moving' a document to new relationship and maintaining all the child relationships?
Thanks!
Hi,
I am using mongoose-materialized to view the data in tree structure, now I got the requirement to modify the tree structure by moving one node to another node, while doing this all the child nodes associated with moving node should move as well.
So can you please help me how to achieve this by modifying the parent and path of the moving node and its sub nodes using mongoose-materialized.
I have some problem to fetch children of node, my data is:
{
"_id": "56fbcfde91c3eca907b561b0",
"path": "56fbcfde91c3eca907b561b0",
"name": "root"
}
{
"_id": "56fbd401947323790b06c02b",
"path": "56fbcfde91c3eca907b561b0#56fbd401947323790b06c02b",
"name": "1",
"parent": "56fbcfde91c3eca907b561b0"
}
{
"_id": "56fbd405947323790b06c02c",
"path": "56fbcfde91c3eca907b561b0#56fbd401947323790b06c02b#56fbd405947323790b06c02c",
"name": "2",
"parent": "56fbd401947323790b06c02b"
}
{
"_id": "56fbd408947323790b06c02d",
"path": "56fbcfde91c3eca907b561b0#56fbd40c947323790b06c02e#56fbd408947323790b06c02d",
"name": "3",
"parent": "56fbd40c947323790b06c02e"
}
{
"_id": "56fbd40c947323790b06c02e",
"path": "56fbcfde91c3eca907b561b0#56fbd40c947323790b06c02e",
"name": "4",
"parent": "56fbcfde91c3eca907b561b0"
}
The tree should be:
root
-1
--2
-4
--3
the path property is correctly set: 3 path is 56fbcfde91c3eca907b561b0#56fbd40c947323790b06c02e#56fbd408947323790b06c02d
translatable into root 4 3
.
When I use rootcat.getChildrenTree({options:{sort:'order'}}, callback);
the result is:
1
--2
--3
4
but if I don't use the order strategy rootcat.getChildrenTree(callback);
the result is right!
I using mongoose v4.4.10, nodejs v0.10.25 and mongodb v3.2.1
I would like to know what the best solution to handling bulk operations is. For example, a common situation is having a tree on the front end (much like http://dbushell.github.io/Nestable/), the user reorders it and we get a nice array with the entire structure on the backend.
What is the most efficient way to update the existing tree?
Hi;
I have following code:
var query = {
condition: {
},
fields: {
},
sort: {
order: 1
}
};
Entity.findOne({
_id: req.params.entityid
}, function(err, doc) {
if (err) res.json(err);
doc.getArrayTree(query, function(err, tree) {
if (err) res.json(err);
return res.json({
type: true,
data: tree
});
});
});
I see that children nodes are not sorted. When I debug, I saw that comes sorted until ToArrayTree was called.
How can we fix it?
When using Cat.GetArrayTree()
it seems that error
is being returned as [Error: null]
instead of just null
.
If I use the plugin as is, I get a warning:
DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated,
plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
If I replace the default Mongoose promise library with the ES6 promise library
mongoose.Promise = global.Promise;
I get an error from your code:
Error: Can't use ES6 promise with mpromise style constructor
Any Ideas?
Hi;
I have the following code:
doc.getArrayTree({
sort: {
order: 1
}
}, function(err, tree) {
if (err) res.json(err);
return res.json({
type: true,
data: tree
});
});
Order is not changes if I retrieve data like that. Where am I wrong?
Is there a way to get the tree structure with ObjectId references populated?
E.g. Lets say I have a tree structure like the simplified structure below, where the users being stored as ObjectId references:
{
title: "Clean House",
users: ["Bob", "Sam"],
children: [
{
title: "Clean Kitchen",
users: ["Bob", "Sam"],
children: [
{
title: "Clean Oven",
users: ["Bob"]
},
{
title: "Clean Sink",
users: ["Sam"]
}
]
}
]
}
Is it possible for the results of getArrayTree to contain the populated users, instead of their ObjectId's?
I wan't to dynamically update a document (so I don't know which key/values get passed to the save function). And the key/values can be nested prety deep, Once again you don't know how deep.
Currently I do this by first getting the document from the database and extend it with the data passed to the update. However this way the document also get converted to a plain object (toObject()).
Big downside of this is that we can't use the .save() method any more because it has become a plain object. Big no no of this story is that the parentId is (maybe) updated in the progress but the path doesn't get updated.
Is there some way to dynamically update a deep nested document while also updating the materialized path?
Maybe it's a idea to also make a method which will only update a specific document its path (or starting from that document it's path and recursively do all it's children), much like the .Building does now but only from the updated document it's id.
Note: to explain it a bit more, this is what is basically wanna do but in less functions (somehow this doesn't work though. The parentId does get updated but the path doesn't)
node = extend(true, node.toObject(), data);
Node.findByIdAndUpdate(data._id, node, function(err, doc) {
Node.findById(doc._id, function(err, savedNode) {
console.log(savedNode.parentId);
savedNode.setParent(savedNode.parentId);
savedNode.save(callback);
});
});
I am planning to version 2.0.
These look forward to ideas that are essential to making this a useful plugin is.
Hello,
To move children from one parent to another, would you first get the new parent document, then get all of the children to move, iterate through them and use appendChild
with the new parent document. Then use the Remove
method to remove from the old parent? Or is there a better method for moving nodes around?
Thanks!
tried to use the setParent to change the parentId and the path, looks like only the parentId is changed, the actual path is not updated. anyone had the same issue?
Also, wondering if setParent will update the children's paths as well?
Hi I'm not sure am I right, but I think I found an issue.
The sort is not working at all.
I have a multi level tree list what I'm want to use as menu.
Here is my data and code
issue.zip
I save model normaly with .save() method as in docs specified. But if I apply, lets say, a new parent - not all children paths are rebuilt. I use 0.1.8 version of your plugin. What could be wrong?
Hello;
I want to use this query in getArrayTree.
var query = {
condition: {
},
fields: {
_id: 1,
name: 1,
description: 1,
price: 1,
type: 1,
image: 1,
published: 1,
children: 1
},
// sorting
sort: {
order: 1
}
};
but children is not coming. Where am I wrong?
Probably not working due to mpromise being deprecated on Mongoose 5, getting 'promise resolver undefined is not a function' while running any method.
Hi,
moving to mongoDB 3.2.9 got problem with limit
https://github.com/florianholzapfel/express-restify-mongoose/issues/
to fix changed --
schema.method('getDescendants', function () {
var query = new Query(arguments);
var promise = new mongoose.Promise;
if (query.callback)
promise.addBack(query.callback);
var self = this;
query.condition.path = {
$regex: (self.path ? '' : '^') + options.separator + self._id.toString()
};
query.sort.path = 1;
query.sort._w = query.sort._w || 1;
query.sort._w = 1;
var cursor = self.constructor.find(query.condition, query.fields)
.sort(query.sort);
if (query.limit)
cursor.limit(parseInt(query.limit)); <------------------------------------------- changed
if (query.skip)
cursor.skip(query.skip);
cursor.exec(function (err, data) {
if (err)
promise.error(err);
else
promise.complete(data);
});
return promise;
});
Expected behaviour: When saving a document with id in parentId field that doesn't point to any document in database, document validation should fail with descriptive error message
Current behaviour: When saving a document with id in parentId field that doesn't point to any document in database, the app crashes with a very non-descriptive error
Steps to recreate:
{
"name": "test-project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index"
},
"author": "",
"license": "ISC",
"dependencies": {
"mongoose": "^5.8.7",
"mongoose-materialized": "^0.2.0"
}
}
const mongoose = require('mongoose')
const materializedPlugin = require('mongoose-materialized')
const { Schema } = mongoose
const TestSchema = new Schema({
name: {
type: String,
required: 'missing_name'
}
})
TestSchema.plugin(materializedPlugin)
mongoose.model('Test', TestSchema)
const { resolve } = require('path')
const mongoose = require('mongoose')
require(resolve('./models/test.model.js'))
const Test = mongoose.model('Test')
const run = async () => {
await mongoose.connect(`mongodb://localhost:27017`, {
dbName: 'test-project',
useNewUrlParser: true
})
const testDoc = new Test({
name: 'test name',
parentId: mongoose.Types.ObjectId()
})
await testDoc.save()
}
run()
Result:
โ test-project npm start
> [email protected] start /Users/user/Documents/projects/test-project
> node index
(node:439) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
(node:439) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
events.js:183
throw er; // Unhandled 'error' event
^
TypeError: done is not a function
at /Users/user/Documents/projects/test-project/node_modules/mongoose-materialized/lib/materialized.js:142:28
at /Users/user/Documents/projects/test-project/node_modules/mongoose/lib/model.js:4784:16
at /Users/user/Documents/projects/test-project/node_modules/mongoose/lib/utils.js:276:16
at /Users/user/Documents/projects/test-project/node_modules/mongoose/lib/model.js:4803:21
at _hooks.execPost (/Users/denisb/Documents/projects/test-project/node_modules/mongoose/lib/query.js:4364:11)
at /Users/user/Documents/projects/test-project/node_modules/kareem/index.js:135:16
at _combinedTickCallback (internal/process/next_tick.js:132:7)
at process._tickCallback (internal/process/next_tick.js:181:9)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `node index`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/user/.npm/_logs/2020-01-17T12_16_06_157Z-debug.log
Node version: 8.16.2
Hello;
I started to use bluebird as default Promise library for Mongoose because of Mongoose's deprecation warning. But now mongoose-materialized is giving error. I wrote it to Stackoverflow but still no solution.
http://stackoverflow.com/questions/41900767/im-getting-cant-use-es6-promise-with-mpromise-error
How to handle this error?
Hy everbody,
many thanks for the great work you did with this great mongoose plugin !
I want to store hierarchical data which uses mongoose schema inheritance by using Discriminators (http://mongoosejs.com/docs/discriminators.html)
By debugging I experienced that this is not working in version 0.1.9.
I prepared the following sample code:
var mongoose = require('mongoose');
var materializedPlugin = require('mongoose-materialized');
mongoose.connect('mongodb://localhost/test');
var Schema = mongoose.Schema;
//Scheme inheritance setup
var ShapeSchema = new Schema({
name: String
}, {discriminatorKey: 'kind'});
ShapeSchema.plugin(materializedPlugin);
var Shape = mongoose.model('Shape', ShapeSchema);
var Circle = Shape.discriminator('Circle', new Schema({radius: Number}));
var Square = Shape.discriminator('Square', new Schema({side: Number}));
var rootShape = new Circle({radius: 5});
//var childShape = new Circle({radius: 5}); //-> THIS IS WORKING
var childShape = new Square({side: 5}); //-> NOT WORKING
rootShape.save(function (err) {
if(err){
console.log(err);
return;
}
rootShape.appendChild(childShape, function (err) {
if(err){
console.log(err);
return;
}
console.log("SUCCESS");
});
});
If I append childs of the same type everything is working fine.
However if I append childs of a different type (Circle -> Square in this example) I get
Error: Parent not found!
As far as I saw using self.constructor (https://github.com/janez89/mongoose-materialized/blob/master/lib/materialized.js#L139) for the findOne(...) operation is causing this issue.
Therefore my suggestion to solve this issue would be to use the native mongodb collection instead:
self.collection.findOne(byId(self.parentId), addId({path: 1}), function (err, parent) {...}
Have you ever experienced this issue ?
Thanks for help
Hi, thank you for the great plugin!
Could you please show how to extract all items for the select input but with indentation?
Something like that:
root
-sub cat
--sub sub cat
Currently, I have recursive function:
function iterate(current) {
if (!current) return;
console.log(current.name);
if (current.hasOwnProperty('children')) {
var children = current.children;
for (var i = 0, len = children.length; i < len; i++) {
iterate(children[i]);
}
}
}
So, needs list of elements which looks like tree (with information about deepness of course)
Hi;
How can I duplicate a tree? Should I Iterate over the tree? Or any suggestions?
Thanks
Hello,
I seem to be getting parent is not defined
anytime I call:
Cat.AppendChild('_id', {name : 'test'}, function(err, doc){});
If I don't specify an 'id' value and instead leave it null, it seems to work. However if I put in an object id or the full model, it always says parent is not defined and errors out.
Any idea what could be causing this? Below is a short trace:
at TCP.onread (net.js:526:21)ReferenceError: parent is not defined at Promise.<anonymous> (/var/www/Proj/server/node_modules/mongoose-materialized/lib/materialized.js:153:33)
Thanks!
Is there anyway to maintain a sort direction with this? For example, let's say we have 5 children, but we want the children to be in a particular order?
Thank you
Hi Janez,
Thanks a lot for this great module :)
It would be nice if you could fix the following bug:
When I assign null to the parentId (i.e. when the specific item should not have any parent anymore - item.parentId = null), then there is no re-arrangement of the hierarchical structure (i.e. no "re-parenting").
The current workaround might be using the "remove" method - which is much less intuitive, and requires to either save the state of the previous parent Id, or to compare the current and previous parent Id values - before saving the item.
Thanks,
Victor
There hasn't been an update with this package for a couple years and there are still a few bugs in it that need to be worked out.
We've created a forked project where we can continue development. So if you have any issues with this lib and they haven't/aren't being addressed you can head over to this github or this npm module.
So far we have implemented the following fixes:
If you have any questions or concerns you can reach us at: [email protected]
Thanks!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.