Can't change result from MongoDB/MongooseJS in route before sending it to the view (Node js)

can definition
can synonym
can verb
can noun meaning
can bus
can band
cant
can't

In my route I am trying to replace a value in whatever i get from the database before sending it to my view.

In this case I am trying to replace a reference to a user, with the users username instead. But my console.log's just keep returning the value unchanged.

app.get('/message/inbox', function(req, res) {
    var _id = req.user._id;
    var inbox = null;
    var users = null;
    async.parallel([
        function(callback){
            Inbox.find({to: _id}, callback);
        },
        function(callback){
            User.find({}, callback);
        }
    ],
    function(err, result){
        inbox = result[0];
        users = result[1];
        for(var i = 0; i < inbox.length; i++) {
            for(var j = 0; j < users.length; j++) {
                if(String(inbox[i].from) == String(users[j]._id)) {
                    inbox[i].from = users[j].local.username;
                    console.log(users[j].local.username);
                    console.log(inbox[i].from);
                    break;
                }
            } 
        }
        console.log(inbox);
    });
});

This is what my console returns:

some@email.com
540468daeb56d5081ade600d
[ { _id: 54084cacf212815422aabe94,
    from: 540468daeb56d5081ade600d,
    to: 5406bf4c8a8acc88120922dc,
    headline: 'Some Headline',
text: 'Some text',
__v: 0 } ]

What gets returned from the find requests is a "mongoose document" which is actually quite complex and contains all the rules and methods from the associated schema. You cannot modify this outside of the constraints set on the schema.

So despite the simple serialized form, the object is quite complex. What you want is just a basic object, so you can modify it however you want. So put simply, just call .toObject() to get the "raw" JavaScript object without the rest of the sugar:

inbox = result[0].toObject();
users = result[0].toObject();

The basic objects have no methods and no rules. Modify away.

Can, Can may refer to: Contents. 1 Containers; 2 Music; 3 Other; 4 See also. Containers[edit]. Aluminum can � Drink can � Oil can � Steel and tin cans � Trash can� Can definition, to be able to; have the ability, power, or skill to: She can solve the problem easily, I'm sure. See more.

Solution by OP.

I just have to add a .lean() after the .find. This tells mongoose to pass the data as a javascript object instead of a MongooseDocument - Scource

app.get('/message/inbox', function(req, res) {
    var _id = req.user._id;
    var inbox = null;
    var users = null;
    async.parallel([
        function(callback){
            Inbox.find({to: _id}, callback).lean();
        },
        function(callback){
            User.find({}, callback).lean();
        }
    ],
    function(err, result){
        inbox = result[0];
        users = result[1];
        for(var i = 0; i < inbox.length; i++) {
            for(var j = 0; j < users.length; j++) {
                if(String(inbox[i].from) == String(users[j]._id)) {
                    inbox[i].from = users[j].local.username;
                    console.log(users[j].local.username);
                    console.log(inbox[i].from);
                    break;
                }
            } 
        }
        console.log(inbox);
    });
});

Can, Can was the leading avant-garde rock group of the 70s. Can experimented with noise, synthesizers, non-traditional music, cut-and-paste techniques, and, most� Define can. can synonyms, can pronunciation, can translation, English dictionary definition of can. to be able to, have the power or skill to: I can take a bus to the

/*
 you just need to add .lean() at the end of mongoose query where you want to change the object later stage.
*/
let forExample = aysnc (req, res, next ) => {
let foundUser = await user.find({ organisationId: 10 }); // without lean
foundUser.map(elem => {
  elem.userName = elem.name;
  delete elem;
});
console.log(foundUser[0]); // it will return { name:'something'};
// but if you try:
let foundUser = await user.find({ organisationId: 10 }).lean();// with lean
foundUser.map(elem => {
  elem.userName = elem.name;
  delete elem;
});
console.log(foundUser[0]); // it will return { userName:'something'};

The Official CAN / Spoon Records Website, VerbEdit. can (third-person singular simple present can, present participle -, simple past could, past participle (obsolete except in adjectival use) couth). can definition: 1. to be able to: 2. used to say that you can and will do something: 3. to be allowed to: . Learn more.

can, 1.4Used to indicate that something is typically the case. 'antique clocks can seem out of place in modern homes'. More example sentences. 110 synonyms of can from the Merriam-Webster Thesaurus, plus 97 related words, definitions, and antonyms. Find another word for can. Can: to bring (as an action or operation) to an immediate end.

Can, can noun [C] (CONTAINER) � can verb [T] (CONTAIN) � can modal verb (ABLE) � can modal verb (PERMIT) � can modal verb (BE POSSIBLE) � can� Etymology 1 From Middle English can, first and third person singular of connen, cunnen (“to be able, know how”), from Old English can (n), first and third person singular of cunnan (“to know how”), from Proto-Germanic *kunnaną, from Proto-Indo-European *ǵneh₃- (whence know).

CAN, Word forms � 1. countable noun A can is a metal container in which something such as food, drink, or paint is put. � 2. verb [usually passive] When food or drink is� HANGZHOU, China, Aug. 04, 2020 (GLOBE NEWSWIRE) -- Canaan Inc. (NASDAQ: CAN) ("Canaan" or the "Company"), a leading high-performance computing solutions provider, today announced that the terms of

Comments
  • possible duplicate of stackoverflow.com/questions/9952649/…
  • I found this solution other places, but it kept returning "has no method 'toObject'"
  • @JesperNielsen Then why change your title to (solved)? It either works or it doesn't
  • @NielLunn - Look at my updated post. I found my own solution.
  • @JesperNielsen Still don't understand why this is not a solution as it works for me and everyone else using mongoose. Of course you can just manually assign every property to a new object as you have done, but I don't call that a solution.
  • I later got it to work. I had a problem where I didn't have access to any of the mongoose functions. I have solved this now and .toObject works as it should now.
  • Try to add some description with your code for clarification of what your code does ? how it solve the problem?