【问题标题】:Adding to object with dot notation not working in Mongoose使用点符号添加到对象在 Mongoose 中不起作用
【发布时间】:2026-02-15 04:35:01
【问题描述】:

我遇到了 Mongoose 中最奇怪的问题。我有以下对象:

        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 添加了另外三个属性,但没有添加任何内容。

【问题讨论】:

  • 这个问题似乎是关于 Javascript 和 Mongoose,而不是关于 Express。我建议修改标题和标签以反映这一点,并可能吸引那些了解猫鼬的问题。
  • 请显示您在运行此程序时得到的确切 console.log() 输出。
  • 我无法完全理解这个问题!什么不适用于点符号?
  • jfriend00,我已经编辑了标签和标题,谢谢。我还添加了控制台日志。

标签: javascript node.js object express mongoose


【解决方案1】:

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

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

【讨论】: