添加到带有点符号的对象在猫鼬中不起作用

Adding to object with dot notation not working in Mongoose

本文关键字:不起作用 对象 符号 添加      更新时间:2023-09-26

我在猫鼬身上遇到了最奇怪的问题。我有以下对象:

        var gameInfo = { "id": $scope.gamedata._id, "role": role, "equipment": "", "notes": "" };

我使用 Node 将其发送到以下函数:

app.put('/userJoin/:userid', function (req, res) {
    console.log("app user join data: " + JSON.stringify(req.body));
    var userid = req.params.userid;
    var u_id = new mongoose.Types.ObjectId(userid);
    var query = { _id: u_id };
    User.findOne(query).exec(function (err, tempuser) {
        console.log(JSON.stringify(tempuser));
        if (tempuser.games == null) {
            console.log("creating games list");
            tempuser.games = [req.body];
            tempuser.x = 5;
            tempuser.shoes = "red";
            console.log("created games list");
        }
        else {
            console.log("adding to games list");
            tempuser.games.push(req.body);
        }
        console.log(JSON.stringify(tempuser));
        tempuser.save(function (err) {
            if (err) { res.send(err); }
            else { res.status(200).end(); }
        });
    });
});

在其中,我使用User.findone(query)从数据库中检索一个用户,并且由于它还没有属性游戏,因此if块会触发,并且我在控制台中看到creating games listcreated games list。但是,我也使用控制台检查if块前后,tempuser对象根本没有变化。由于我在之前和之后检查,我几乎可以确定故障一定在if块内,但我无法弄清楚原因。

编辑:为了澄清起见,这是服务器端控制台的输出:

app user join data: {"id":"56e06bf57b05ae040e4227ae","role":"2","equipment":"","notes":""}
{"_id":"56e84cce39f024241eaa0b7f","__v":0,"password":"03c7c0ace395d80182db07ae2c30f034","username":"a"}
creating games list
created games list
{"_id":"56e84cce39f024241eaa0b7f","__v":0,"password":"03c7c0ace395d80182db07ae2c30f034","username":"a"}

如您所见,尽管使用点表示法向 tempuser 添加了另外三个属性,但尚未添加任何内容。

快步走过后,答案突然出现在我的脑海中,我已经验证了它是正确的。问题在于我对猫鼬的一些基础知识缺乏了解,对框架不熟悉。

User.findOne(query).exec(function (err, tempuser)检索到猫鼬模型,而不是普通的javascript对象,正如我意识到的那样,模型在创建后不能直接更改(只能更新它们的值)。games:[]数组不是模型的一部分,因此我无法添加它。