【问题标题】:How to insert and update existing data in database using nodejs?如何使用 nodejs 插入和更新数据库中的现有数据?
【发布时间】:2019-04-08 14:18:36
【问题描述】:

我已经创建了消息模式和对话模式。我无法理解为什么我无法将数据存储在 mongodb 中。

messageschema.js:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create Schema
const MessageSchema = new Schema({
  author: {
    type: String,
    required: true,
  },
  message: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model('Message', MessageSchema);

conversationschema.js:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create Schema
const ConversationSchema = new Schema({
  user1: {
    type: String,
    required: true
  },
  user2: {
    type: String,
    required: true
  },
  conversations : [{ type: Schema.Types.ObjectId, ref: 'Message' }]

});

module.exports = mongoose.model('Conversation', ConversationSchema);

server.js:

let db = mongoose.connection;
var user1, user2;

db.once('open', function() {
  console.log("Database is now connected");

  let io =  socket(server);

io.on("connection", function(socket){
  console.log("Socket Connection Established with ID :"+ socket.id)

  socket.on('disconnect', function(){
    console.log('User Disconnected');
  });

  let chat = db.collection('chat');
  let conversation = db.collection('conversation'); 

      socket.on('GET_USER', function (data) {
        console.log(data);
         user1 = data.user2;
      });

      socket.on('LOGGEDIN_USER', function(data) {
        console.log(data);
         user2 = data.user1;
      });

      socket.on('SEND_MESSAGE', function(data){

        let author = data.author;
        let message = data.message;
        let date = data.date;

        // Check for name and message
        if(author !== '' || message !== '' || date !== ''){
            // Insert message
            chat.insert({author:author, message: message, date:date}, function(){
              io.emit('RECEIVE_MESSAGE', [data]);
            });

            conversation.findOneAndUpdate(
              { user1 : user1, user2: user2 }, 
              { conversations : { $push : { author, message, date } } },
              { upsert : true}
            );

        }
      });

在 server.js 中,我想在对话(对话是一个数组)中添加消息,在对话集合中添加 user1 和 user2(user1,user2 是字符串)。因此,如果未在 user1 和 user2 之间创建对话,则创建新对话并将其存储在集合中。如果存在先前的聊天,即会话中存在消息,则只需将消息推送到会话数组中。我已经在上面的 server.js 中实现了它,但是文档没有被插入到对话集合中。文档仅添加聊天集合。

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    你可以像下面这样尝试 $push : { conservations : <<jsonObject.>>}

    例子

     conversation.findOneAndUpdate(
            { user1 : user1, user2: user2 }, 
            { $push : {conversations : { author : 'author',message : 'message',date : 'date' }}},
            { upsert : true}
        );
    

    【讨论】:

      【解决方案2】:

      您错误地使用了findOneAndUpdate 函数。第二个论点是不正确的。请查看 mongoDB 文档 (db.collection.findOneAndUpdate) 以了解如何正确使用它。在那里,你可以找到

      参数:更新 类型: 文档
      说明: 要应用的修改。 使用更新运算符,例如 $set$unset$rename。 使用 field: value 的 update() 模式更新参数会引发错误。

      conversation.findOneAndUpdate(
          { user1 : user1, user2: user2 }, 
          { conversations : { $push : { author, message, date } } }, // <<---- not OK
          { upsert : true}
      );
      

      您需要在第二个参数处使用$set

      { $set: <your object> }
      

      【讨论】:

      • 为什么需要 $set ?如果对话数组不为空,我只想从消息模式推送消息。如果它为空,则插入新文档,即消息。注意:我在对话模式中使用 ref
      • @funjoker $set 是必需的,因为 findOneAndUpdate() 需要它作为其语法的一部分。你想设置一个字段的值,所以你需要在这个中使用$set。如文档页面中所述,除了$set,您还可以在update operators list 中使用$unset$rename 或任何其他运算符
      猜你喜欢
      • 2018-01-29
      • 2020-07-11
      • 1970-01-01
      • 2019-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-23
      相关资源
      最近更新 更多