MongoDB 和 mongoose:如果对象不存在,如何添加它

编程入门 行业动态 更新时间:2024-10-25 10:24:04
本文介绍了MongoDB 和 mongoose:如果对象不存在,如何添加它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在使用 mongoDB/mongoose 和 node.js 时遇到了一些问题.我习惯了 SQL,而 mongoDB 是......很难!这是我的架构:

I am having some trouble with mongoDB/mongoose and node.js. I am used to SQL, and mongoDB is...hard! Here is my schema:

var mongoose = require('mongoose');

var mongoose = require('mongoose');

mongoose.Promise = global.Promise;

mongoose.Promise = global.Promise;

var itemSchema= mongoose.Schema({ item_info : { user_id : Number, location : String, item_id : Number, title : String }, item_hist : { user_id : Number, location : String, item_id : Number, founddate : String } }); module.exports = mongoose.model('item', itemSchema);

我可以通过这样做添加一个新项目:

And I can add a new item by doing this:

var item= require('./app/models/item'); var item= new item(); item.item_info.user_id = 12345; item.item_info.location = 'This address'; item.item_info.item_id = 4444; item.item_info.title = 'New item'; item.save(function(err) { if (err) throw err; });

我希望能够做的是说:查找 item_info.item_id 5555 的项目.如果它存在,什么都不做.如果它不存在,则将其添加到数据库."我已经阅读了很多 mongodb 和 mongoose 文档,但是在使用点符号和通过 nodejs 而不是命令行 mongodb 访问之间,我仍然无法弄清楚如何做到这一点.SQL 看起来简单多了!

What I want to be able to do is say: "look for an item with item_info.item_id 5555. if it exists, do nothing. if it doesn't exist, then add it to the database." I've read through so much mongodb and mongoose documentation, but between using dot notation and accessing through nodejs instead of command line mongodb, I still can't figure out how to do this. SQL seemed so much easier!

推荐答案

就用这个 -

var query = { user_id: 12345, location: "This address", item_id: 4444, title: "New item" }, options = { upsert: true }; Model.findOneAndUpdate(query.item_id, query, options, function(error, result) { if (error) return; // do something with the document });

更多推荐

MongoDB 和 mongoose:如果对象不存在,如何添加它

本文发布于:2023-10-07 10:36:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1469160.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不存在   对象   MongoDB   mongoose

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!