我正在尝试删除元素数组,但是根本无法正常工作。
在模式中
var connectedUsers = Schema({
fruits: { type: Array },
vegetables: { type: Array }
})
var connectedusers = mongoose.model("connectedusers", connectedUsers)
Node js路由文件
router.post('/connectedusers', function(req,res) {
connection.connectedusers.update(
{ $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } },
{ multi: true }
)
connection.connectedusers.find({}, function (err, docs) {
if (err) throw err;
res.json({
docs: docs
})
})
});
在mongodb集合中
{
"_id": {
"$oid": "5cef68f690a42ba057760e98"
},
"__v": 0,
"connectArray": [
"vinay",
"vinay1"
],
"fruits": [
"apples",
"pears",
"oranges",
"grapes",
"bananas"
],
"vegetables": [
"carrots",
"celery",
"squash",
"carrots"
]
}
元素数组未删除..其显示所有集合详细信息。 如何使用$ Pull或其他任何方法从mongodb中删除元素。
答案 0 :(得分:0)
请尝试以下操作:
router.post('/connectedusers', function(req,res) {
connection.connectedusers.update(
{}, // Missing query part
{
$pull: {
fruits: { $in: [ "apples", "oranges" ] },
vegetables: "carrots"
}
},
{ multi: true }
)
connection.connectedusers.find({}, function (err, docs) {
if (err) throw err;
res.json({
docs: docs
})
})
});
您的查询工作正常,我在最后尝试了它。您缺少MongoDB update函数的查询部分
答案 1 :(得分:0)
您忘记了匹配查询,数据库功能也是asynchronous,因此您需要await才能完成更新操作,然后再查询以检查数据库是否已更改,这可以通过{ {3}}
// change callback to an async arrow function
router.post('/connectedusers', async (req, res) => {
try {
// wait for this operation to complete before continuing
await connection.connectedusers.update(
{},
{ $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } },
{ multi: true }
);
// update complete now wait for the find query
const docs = await connection.connectedusers.find({});
// no errors, send docs.
// if the variable name is the same as your field
// that you want to send in the object you can just
// pass that variable directly
res.json({ docs });
// catches errors from both update and find operations
} catch (err) {
// set the status code and send the error
res.status(/* error status */).json(err);
}
});