[英]Adding a new key in mogoDB collection using mongoose
Take a scenario where my current collection named fruits looks like:假设我当前的名为 fruits 的集合如下所示:
{"_id" : ObjectId("xyz...."), "name" : "Apple", "rating" : 7}
{"_id" : ObjectId("abc...."), "name" : "Banana", "rating" : 9}
{"_id" : ObjectId("lmn...."), "name" : "Kiwi", "rating" : 8}
Now, if I intend to add a new key-value pair (key named quantity) only in the second doc (ie, where name: Banana), I would do the following in the terminal using mongoDB:现在,如果我打算仅在第二个文档(即名称:Banana)中添加一个新的键值对(键名为数量),我将使用 mongoDB 在终端中执行以下操作:
db.fruits.updateOne({name : "Banana"},{$set:{quantity : 20}})
and now my collection would look like the following:现在我的收藏将如下所示:
{"_id" : ObjectId("xyz...."), "name" : "Apple", "rating" : 7}
{"_id" : ObjectId("abc...."), "name" : "Banana", "rating" : 9}
{"_id" : ObjectId("lmn...."), "name" : "Kiwi", "rating" : 8, "quantity" : 20}
So how do I achieve the same thing using mongoose in my app.js.那么如何在我的 app.js 中使用 mongoose 来实现相同的目标。 I don't want to change the entire schema for all the docs, becoz mongoDB is a NOSQL and a structure should not be cumpulsory.我不想更改所有文档的整个架构,因为 mongoDB 是 NOSQL 并且结构不应该是强制性的。
You should define a schema corresponding to the collection, let's call it fruit.model.js
:你应该定义一个对应于集合的模式,我们称之为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;
And the use it to run your query using the findOneAndUpdate
method:并使用findOneAndUpdate
方法使用它来运行您的查询:
const mongoose = require('mongoose');
const Fruit = require('./fruit.model');
const updateFruit = async () => {
await Fruit.findOneAndUpdate({ name: "Banana" }, { quantity: 20})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.