【问题标题】:Doubts on Mongodb query对MongoDB查询的质疑
【发布时间】:2023-03-29 05:12:01
【问题描述】:

我正在使用 MERN 堆栈设计分类广告网络应用。 MongoSchema如下图

const UserSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    books: [{
        title: { type: String },
        author: { type: String },
        desc: { type: String },
        price: { type: String },
        image: { data: Buffer, contentType: String }
    }],
    date: {
        type: Date,
        default: Date.now
    }
});

因此,除了books[] 之外的所有其他信息将在初始注册后可用,但我想做的是每次用户希望发布一本书进行销售时更新books 数组。

我计划通过id 查找用户,但我不太确定如何将信息添加/附加到books 数组。

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    您的问题已经在 Stackoverflow 中提供了一些答案。 例如: Using Mongoose / MongoDB $addToSet functionality on array of objects

    你可以这样做:

    UserModel.js

    const mongoose = require("mongoose");
    
    const UserSchema = new Schema({
        name: {
            type: String,
            required: true
        },
        email: {
            type: String,
            required: true
        },
        password: {
            type: String,
            required: true
        },
        books: [{
            title: { type: String },
            author: { type: String },
            desc: { type: String },
            price: { type: String },
            image: { data: Buffer, contentType: String }
        }],
        date: {
            type: Date,
            default: Date.now
        }
    });
    module.exports = User = mongoose.model("user", userSchema);
    

    之后,在您的路由器文件中,您可以为 books 数组尝试这样的操作:

    const res = await User.updateOne({ email: 'gintama@bandainamco.com' }, {'$addToSet':{
    'books':{
            title: "Gintama: The Final",
            author: "Sorachi",
            desc: "Final Arc",
            price: "44.99",
            image: "src"
        }}); //addToSet if you don't want any duplicates in your array.
    

    const res = await User.updateOne({ email: 'gintama@bandainamco.com' }, {'$push':{
        'books':{
                title: "Gintama: The Final",
                author: "Sorachi",
                desc: "Final Arc",
                price: "44.99",
                image: "src"
            }}); //push if duplicates are okay in your array
    

    【讨论】:

    • 谢谢,所以addToSet 是我所缺少的。
    • 是的。在某些可能使用定量数值数组的情况下,您将需要 push 运算符。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 2020-08-01
    • 2015-01-01
    • 1970-01-01
    • 2014-02-03
    • 2016-11-28
    • 2014-10-10
    相关资源
    最近更新 更多