【问题标题】:Can't add a new property to an object returned by Mongoose query [duplicate]无法向 Mongoose 查询返回的对象添加新属性 [重复]
【发布时间】:2015-03-25 07:22:33
【问题描述】:

我正在使用 Node.js、MongoDB 和 Express 编写 API。我似乎无法向正在迭代的位置对象添加新属性。

我完全不明白我的代码存在的问题。 loc 是一个普通的对象,它应该可以工作。我错了吗?

// **********************************
// GET Locations
// **********************************
// Create endpoint /api/locations for GET

exports.getLocations = function(req, res) {

    // Use the Location model to find all locations
    // of a particular user

    Location.find({}, function(err, locations) {
        if (err)
            res.send(err);
        var counter = 0;
        var l = locations.length;

        //we create a closure to access the current location object
        var closure = function(location) {

             //we are returning the callback
             return function(err, user) {
                if (err)
                    res.send(err);
                counter++;
                console.log("The location object: \n"+location+"\n\n");

                console.log("The value we want to add to the object: \n"+user.username+"\n\n");

                //THAT DOESN'T WORK
                location.username = user.username;

                console.log("The updated object: \n"+location+"\n\n");

                if(counter === l) res.json(locations);
            };
        };

        //We respond with the locations
        for (var i = 0; i < l; i++) {

            //we call our function
            User.findById(locations[i].userId, "username", closure(locations[i]));
        }
    });
};

这是我在控制台中得到的输出......这太奇怪了。

The location object:
{ _id: 54c65c665ff13962b6a367a1,
  userId: '54c659ba8ac00324b617f3f9',
  message: 'Big party here tonight!!',
  longitude: 45.5,
  latitude: 73.5667,
  __v: 0 }


The value we want to add to the object:
test123


The updated object:
{ _id: 54c65c665ff13962b6a367a1,
  userId: '54c659ba8ac00324b617f3f9',
  message: 'Big party here tonight!!',
  longitude: 45.5,
  latitude: 73.5667,
  __v: 0 }

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    在我们的例子中,你有 MongooseDocument 而不是 plain JS 对象。为了获得plain JS 对象,您应该像这样使用.lean

    Location.find({}).lean().exec(function(err, locations) {
        ...
    });
    

    【讨论】:

    • 这就是我要找的!关于为什么对象没有更新,我已经摸不着头脑了一个小时
    • 天哪,猫鼬!但为什么?好痛!
    猜你喜欢
    • 2019-05-16
    • 2016-04-05
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    • 2015-05-27
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多