Hi!
I want to add a new field for all Documents
in a collection based on some fields in Roles
that’s dependent on using ‘alanning:roles’.
I’m trying to do this standalone using a simple adhoc script that’s like the following
process.env.MONGO_URL = "URL"
import { Meteor } from "meteor/meteor";
import { Mongo } from 'meteor/mongo';
import { Roles } from 'meteor/alanning:roles';
const Documents = new Mongo.Collection('Documents');
Meteor.startup(() => {
const doc = Documents.find({});
//Get new field from Role and then save
const role = Roles.getUser(doc.foo);
doc.newField = role.field
});
But doc
is undefined after installing Roles
. Wo it, I’m able to print it out. My speculation is that Roles
is doing something with the local MongoDB as opposed to the remote one with the MONGO_URL
. Any Ideas?
I’m certain the package has nothing to do.with it. Most likely it’s your code. For instance, Documents.find({}) will not return a document, but a cursor. You should use collection.findOne()
for one doc or collection.find().fetch() for an array of docs.
1 Like
Collection#find() returns a cursor, see https://docs.meteor.com/api/collections.html#Mongo-Collection-find
So your code would be something like…
...
const documents = Documents.find({}).fetch();
documents.forEach(doc => {
const { _id, foo } = doc;
// Get new field from Role and then save
const role = Roles.getUser(foo);
Documents.update({ _id }, { $set: { newField: role } });
});
If you have a large number of documents, this could be a slow process, and you’d be better off with bulkWrite()
(on Collection.rawCollection()
of course), see https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#bulkWrite
…but if you have just a relatively small amount of documents or time is not an issue, then it’s fine that way.
Yeah, I used findOne
and fetch
to no avail