【问题标题】:使用 mongoose 在 mongoDB 集合中添加新键
【发布时间】:2022-01-23 16:59:19
【问题描述】:

假设我当前的名为 fruits 的集合如下所示:

{"_id" : ObjectId("xyz...."), "name" : "Apple", "rating" : 7}
{"_id" : ObjectId("abc...."), "name" : "Banana", "rating" : 9}
{"_id" : ObjectId("lmn...."), "name" : "Kiwi", "rating" : 8}

现在,如果我打算仅在第二个文档(即名称:Banana)中添加一个新的键值对(键名为数量),我将使用 mongoDB 在终端中执行以下操作:

db.fruits.updateOne({name : "Banana"},{$set:{quantity : 20}})

现在我的收藏将如下所示:

{"_id" : ObjectId("xyz...."), "name" : "Apple", "rating" : 7}
{"_id" : ObjectId("abc...."), "name" : "Banana", "rating" : 9}
{"_id" : ObjectId("lmn...."), "name" : "Kiwi", "rating" : 8, "quantity" : 20}

那么我如何在我的 app.js 中使用 mongoose 来实现同样的目标。我不想更改所有文档的整个架构,因为 mongoDB 是一个 NOSQL,结构不应该是强制性的。

【问题讨论】:

    标签: javascript node.js database mongodb mongoose


    【解决方案1】:

    您应该定义一个与集合对应的架构,我们称之为fruit.model.js

    const mongoose = require('mongoose');
    
    const fruitSchema = new mongoose.Schema({
        name: String,
        quantity: Number
    });
    
    const Fruit = mongoose.model('Fruit', fruitSchema);
    
    module.exports = Fruit;
    

    然后使用它使用findOneAndUpdate 方法运行您的查询:

    const mongoose = require('mongoose');
    const Fruit = require('./fruit.model');
    
    const updateFruit = async () => {
        await Fruit.findOneAndUpdate({ name: "Banana" }, { quantity: 20})
    }
    

    【讨论】:

    • 您是否刚刚创建了关系或在原始集合中进行了更改。我很困惑,因为我当前的模型也被命名为“水果”。
    • 如果您已经定义了模型,则无需重新创建它。您可以使用findOneAndUpdate 方法执行更新查询。如果您需要将其用作 POST 中间件,则需要更改函数的签名以接收 reqres 参数。
    猜你喜欢
    • 1970-01-01
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    • 2019-08-07
    相关资源
    最近更新 更多