用猫鼬添加到数组或更新(如果已经存在)

时间:2019-07-15 11:44:18

标签: arrays node.js mongoose schema subdocument

我有一个带有现场聊天的用户模型,这是聊天消息的子文档。我想建立一个查询,以找到子文档(如果存在)并更新它,或者创建它(如果不存在)。

这些是我的模式

//User Schema (removed unrelated parts)
Schema({
...
    chats: { type: [PrivateMsg] },
...
});

//PrivateMsg schema
Schema({
    from: { type: Schema.Types.ObjectId, ref: 'User', required: true },
    message: { type: [String], required: true }
});

这是我到目前为止尝试过的:

User.findOneAndUpdate({
    _id: "some id"
    "chats.from": "some id"
}, {
        $push: {
            chats: {
            from: "some id",
            $push: {
                message: "test message"
            }
        }
    }
}, {upsert: true, runValidators: true}, (err, resp) => {
    if (err) console.log(err);
    console.log(resp);
})

无法按照我认为的方式工作:p

0 个答案:

没有答案
相关问题