Я пытаюсь удалить массив элементов, но он вообще не работает.
в схеме
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
})
})
});
В коллекции монгодб
{
"_id": {
"$oid": "5cef68f690a42ba057760e98"
},
"__v": 0,
"connectArray": [
"vinay",
"vinay1"
],
"fruits": [
"apples",
"pears",
"oranges",
"grapes",
"bananas"
],
"vegetables": [
"carrots",
"celery",
"squash",
"carrots"
]
}
Массив элементов не удаляется... показывает все детали коллекции. как удалить элементы из mongodb с помощью $Pull или любого другого.
Попробуйте, как показано ниже:
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 Обновить
Вы забыли запрос на соответствие, а также функции базы данных асинхронный, поэтому вам потребуется Ждите для завершения операции обновления, прежде чем запрашивать, чтобы проверить, изменилась ли база данных, это можно сделать с помощью асинхронные функции
// 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);
}
});