javascript - 使用 .push() 时,mongodb 数组类型的字段不会更新长度

标签 javascript node.js mongodb

以下是尝试将用户添加到架构的代码:

var roomSchema = new Schema({
    name: { type: String, required: true},
    connections: { type: [ { userId: String } ] },
    content: { type: String, default: ""},
    isFull: { type: Boolean, default: false}
});

roomSchema.methods.addUser = function(username, callback) {
this.updateAsync( { $push: { connections: { userId: username }  } } )
.then(function(status) {
    return this.saveAsync();
})
.catch(function(afterPushErr) {
    console.log('After push error');
    throw afterPushErr;
})
.catch(function(saveErr) {
    console.log('save Error');
    throw saveErr;
});

Promise.all(this.connections)
.then(function() {
    if(this.connections.length >= 5) {
        this.updateAsync( { isFull: true })
        .then(function(status) {
            return;
        })
        .catch(function(updateErr) {
            console.log('update Error!');
            throw updateErr;
        });
    }
});

}

然后是调用它的代码(正确导入上述函数): (注:这只是一个快速测试功能,以确保每个房间最多只有 5 个用户)

var populateRooms = function() {
    var names = [
        'asas',
        'asas2',
        'asas3',
        'asas4',
        'asas5',
        'asas6'];

    var emails = [
        'asas@as.ca',
        'asas2@as.ca',
        'asas3@as.ca',
        'asas4@as.ca',
        'asas5@as.ca',
        'asas6@as.ca'];

    for(var i=0; i<6; ++i) {
    Room.findOneAsync( { isFull: false })
        .then(function(freeRoom) {
            var newUser = new User({
                username : names[i],
                email : emails[i],
                password : 'Asasas1',
                isPlaced: true,
                roomName: freeRoom.name
            });
            freeRoom.addUser(newUser.username);
            return newUser;
        })
        .then(function(newUser) {
            newUser.saveAsync();
        })
        .catch(function(err) {
            throw err;
        });
    }
    return true;
}

通常我在控制台中看到的只是最后一个被推送的用户而不是整个列表,因此我无法查看列表的长度是否 >= 5。

在 mongo 控制台上,我看到了房间架构:

{ "_id" : ObjectId("5882c3eefab3081700444972"), "name" : "1484964846968_0", "isFull" : false, "content" : "", "connections" : [ { "userId" : "asas5", "_id" : ObjectId("5882c3effab308170044497f") }, { "userId" : "asas6", "_id" : ObjectId("5882c3effab308170044497d") }, { "userId" : "asas4", "_id" : ObjectId("5882c3effab3081700444981") }, { "userId" : "asas6", "_id" : ObjectId("5882c3effab308170044497d") }, { "userId" : "asas5", "_id" : ObjectId("5882c3effab308170044497f") }, { "userId" : "asas4", "_id" : ObjectId("5882c3effab3081700444981") }, { "userId" : "asas3", "_id" : ObjectId("5882c3effab3081700444983") }, { "userId" : "asas", "_id" : ObjectId("5882c3effab3081700444987") }, { "userId" : "asas2", "_id" : ObjectId("5882c3effab3081700444985") }, { "userId" : "asas3", "_id" : ObjectId("5882c3effab3081700444983") }, { "userId" : "asas2", "_id" : ObjectId("5882c3effab3081700444985") }, { "userId" : "asas", "_id" : ObjectId("5882c3effab3081700444987") } ], "__v" : 12 } { "_id" : ObjectId("5882c3eefab3081700444973"), "name" : "1484964846978_1", "isFull" : false, "content" : "", "connections" : [ ], "__v" : 0 } { "_id" : ObjectId("5882c3eefab3081700444974"), "name" : "1484964846980_2", "isFull" : false, "content" : "", "connections" : [ ], "__v" : 0 } { "_id" : ObjectId("5882c3eefab3081700444975"), "name" : "1484964846980_3", "isFull" : false, "content" : "", "connections" : [ ], "__v" : 0 } { "_id" : ObjectId("5882c3eefab3081700444976"), "name" : "1484964846981_4", "isFull" : false, "content" : "", "connections" : [ ], "__v" : 0 } { "_id" : ObjectId("5882c3eefab3081700444977"), "name" : "1484964846981_5", "isFull" : false, "content" : "", "connections" : [ ], "__v" : 0 } { "_id" : ObjectId("5882c3eefab3081700444978"), "name" : "1484964846982_6", "isFull" : false, "content" : "", "connections" : [ ], "__v" : 0 } { "_id" : ObjectId("5882c3eefab3081700444979"), "name" : "1484964846984_7", "isFull" : false, "content" : "", "connections" : [ ], "__v" : 0 } { "_id" : ObjectId("5882c3eefab308170044497a"), "name" : "1484964846984_8", "isFull" : false, "content" : "", "connections" : [ ], "__v" : 0 } { "_id" : ObjectId("5882c3eefab308170044497b"), "name" : "1484964846984_9", "isFull" : false, "content" : "", "connections" : [ ], "__v" : 0 }

编辑 这是 addUser 的 promise 代码上的新错误

(node:4648) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'connections' of undefined (node:4648) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'connections' of undefined After push error After push error save Error save Error Unhandled rejection TypeError: Cannot read property 'saveAsync' of undefined at C:\someApp\app\models\room-model.js:19:14 at tryCatcher (C:\someApp\node_modules\bluebird\js\release\util.js:16:23)

最佳答案

在测试函数中,您将异步调用 (Room.findOne) 放入 for 循环内。因此,每个循环都获得相同的 freeZoom 。(这不是您想要的)

检查这个问题:Asynchronous Process inside a javascript for loop

另一个建议,addUser 函数中的 this.update 也是异步的,在某些情况下可能不会像您想要的那样。

关于javascript - 使用 .push() 时,mongodb 数组类型的字段不会更新长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41775137/

相关文章:

javascript - 将 UTM 值从 URL 推送到隐藏字段的脚本 (Webflow)

javascript - 以 Angular 添加 Controller 特定文档 addeventlistener

javascript - 如何从父html通过iframe传递参数?

javascript - 如何在reactjs中使用条件语句渲染组件?

javascript - 检查文件是否同步存在是什么意思?

python - Mongoengine 中的 "QuerySet"对象到底是什么?

javascript - 更新标记文本谷歌地图API

node.js - 如何对post请求中传递的表单数据进行编码

mongodb - 在 MongoDB 上聚合后返回完整文档

php - MongoDB NumberLong 在 PHP 中显示