gpt4 book ai didi

javascript - findOneAndUpdate Mongoose 函数中的字符串文字问题

转载 作者:可可西里 更新时间:2023-11-01 10:26:30 25 4
gpt4 key购买 nike

类似本期https://stackoverflow.com/questions/11183480/how-to-set-key-by-var-in-mongoose-node-js#=我无法在 findOneAndUpdate 函数中获取字段变量。它将它作为文字字段。我试图实现他们的解决方案,但没有奏效。我没有收到错误,它只是没有更新任何内容。

var cat = new Cat();

var field = (req.body[1].type);

Cat.findOneAndUpdate({ 'sid': req.sessionID }, {$push: {field: req.body[0]}}, {'upsert': true, 'new': true}, function (err, data){

最佳答案

您需要使用括号 [] 表示法来将对象属性的“键”设置为变量中的值:

var cat = new Cat();

// Just use it in the below assignment instead
//var field = (req.body[1].type);

var update = { "$push": { } };
update.$push[req.body[1].type] = req.body[0];

Cat.findOneAndUpdate(
{ 'sid': req.sessionID },
update, // and reference in here
{'upsert': true, 'new': true},
function (err, data){

这就是如何在 JavaScript 中动态分配一个键。

关于javascript - findOneAndUpdate Mongoose 函数中的字符串文字问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33489377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com