Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

javascript - Mongo / Mongoose - Push object into document property array on condition

I have a document stored on mongo that, amongst others, contains a property type of an array with a bunch of objects inside. I am trying to push an object to that array. However each object that gets pushed to into the array contains a date object. How I need it to work is if an object with that date already exists then dont push the new object into the array.

I'm been playing with it for a while, trying to run update and elemMatch queries etc, but I can't figure it out. I have a long draw out version below, as you can see I'm making 2 separate requests to the database, can someone help me reduce this to something simpler?

 UserModel.findById(req.user._id, (err, doc) => {
        if (err) {
            return res.sendStatus(401);
        }
        const dateExists = doc.entries.find((entry) => entry.date === date);
        if (dateExists) {
            res.sendStatus(401);
        } else {
            UserModel.findByIdAndUpdate(
                req.user._id,
                {
                    $push: {
                        entries: {
                            date,
                            memo,
                        },
                    },
                },
                { safe: true, upsert: true, new: true },
                (err, doc) => (err ? res.sendStatus(401) : res.sendStatus(200))
            );
        }
    });

Thanks.

question from:https://stackoverflow.com/questions/65648089/mongo-mongoose-push-object-into-document-property-array-on-condition

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
db.users.updateOne({
  _id: req.user._id,
  "entries.date": date,
},
{
    $push: {
         entries: {date,memo},
    }
})

https://docs.mongodb.com/manual/reference/method/db.collection.updateOne/index.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...