问题描述
我试图将一个值推入mongodb集合arrayList(user.completed),但是即使我的代码似乎正确,它也没有得到更新.
I am trying to push a value to mongodb collection arrayList (user.completed) but it's not getting updated even though my code seems correct.
当我进行API调用时,将传递值,但是"$ push"不会为完成的数组添加值!我在这里想念什么?
When I make the API call, the values are being passed however "$push" isn't adding value to completed array!! What am I missing here?
当我尝试将值推送到字符串时,出现猫鼬错误,正如预期的那样.但是,当我尝试将值推入未定义的键('abc')时,不会像mongodb文档建议的那样创建新数组!不知道这是怎么回事!
When I try to push to value to a string, I get mongoose error as expected. But when I try to push value to an undefined key ('abc'), a new array doesn't get created like the mongodb documentation suggest! Not sure what is going on here!
//Mongodb数据
// Mongodb Data
{
"_id" : ObjectId("58aa2eb1de7b414237b93981"),
"email" : "[email protected]",
"firstName" : "test",
"completed" : [],
"playing" : [],
"__v" : 2
//API
import mongoose from 'mongoose'
import { Router } from 'express'
import User from './../model/user'
api.put('/completed/:id', (req, res) => {
User.update(
{ "_id": req.params.id },
{ "$push": {
"completed": req.body.completed
}}
)
.then(doc => res.send(doc), err => res.status(400).send(err))
})
//请求
var request = require("request");
var options = {
method: 'PUT',
url: 'http://localhost:8008/v1/user/completed/58aa2eb1de7b414237b93981',
headers: {
'content-type': 'application/json' },
body: { completed: { game: 'A', player: 'B' } },
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
推荐答案
使用$addToSet
停止复制数组中的相同数据
use $addToSet
to stop duplication of same data in the array
$addToSet
不会将项目添加到给定字段中,如果它已经包含该项目,但是$push
会将给定值添加到字段中,无论该项目是否存在.
$addToSet
won't add the item to the given field if it already contains it, but $push
will add the given value to field whether it exists or not.
User.update({ "_id": req.params.id },
{ $addToSet: { "completed": req.body.completed } }, function (err, d) {
if (!d.nModified) {
// same value entered won't add to the array
} else {
// new value entered and will add to the array
}
});
这篇关于将项目推送到Mongodb集合数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!