简体   繁体   English

mongodb在保存数据时生成相同的ObjectID

[英]mongodb generate the same ObjectID when save data

I'm writing a forum, a user log in and publish posts, I use mongoose to save posts to the mongodb, I found that when a user publishes another post, the mongodb will generate the same ObjectID for all the posts the user publishes, and when the user log out and return, mongodb will generate new ObjectID. 我正在写一个论坛,一个用户登录并发布帖子,我使用mongoose将帖子保存到mongodb中,我发现当用户发布另一个帖子时,mongodb会为该用户发布的所有帖子生成相同的ObjectID,当用户注销并返回时,mongodb将生成新的ObjectID。

here is my code: 这是我的代码:

import mongoose from 'mongoose'
mongoose.Promise = global.Promise
import db from './db'
const PostSchema = new mongoose.Schema({
    author:String,
    title:String,
    content:String,
    time:{}
 });
PostSchema.methods.savePost = function(post,cb){
    const date = new Date();
    const time = {
      date: date,
      year : date.getFullYear(),
      month : date.getFullYear() + "-" + (date.getMonth() + 1),
      day : date.getFullYear() + "-" + (date.getMonth() + 1) + "-" +     date.getDate(),
      minute : date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + 
  date.getHours() + ":" + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) 
    };
    this.author = post.author;
    this.title = post.title;
    this.content = post.content;
    this.time = time;
    this.save(cb);
};

api: api:

postEntity.savePost(post,err=>{
        if(err){
            return res.status(500).end('server err')
        } else {
            console.log('publish successfully')
            return res.status(200).end('success')
        }
    })

here is all the code in my github: https://github.com/laoqiren/isomorphic-redux-forum/tree/master/server 这是我的github中的所有代码: https : //github.com/laoqiren/isomorphic-redux-forum/tree/master/server

Ok, yeah, the issue is that you're only creating one new post. 好的,是的,问题是您只创建了一个新帖子。

In ./api/addPost.js , you do const postEntity = new Post() . ./api/addPost.js ,您执行const postEntity = new Post() That will get called one time (the first time the file is required or imported) and then the same postEntity will be used on all subsequent uses. 这将被调用一次(第一次需要或导入文件),然后将在所有后续使用中使用相同的postEntity。

instead, you can write it like so: 相反,您可以这样编写:

const jwt = require("jwt-simple");
import Post from '../Models/post';

export default function(req,res,next){
    const token = req.body.access_token;
    let name;
    if(token){
        try{
            var decoded = jwt.decode(token,req.app.get('jwtTokenSecret'));
            if(decoded.exp < Date.now()){
                return res.end('token expired',401);
            }
            name = decoded.name;
        } catch(err){
            res.status(401);
            return res.send('no token');
        }
        const post = new Post({
            title: req.body.title,
            content: req.body.content,
            author: name,
            discuss: []
        }); 
        post.save(err => {
            if(err){
                return res.status(500).end('服务器错误')
            } else {
                return res.status(200).end('发表文章成功')
            }
        })
    } else {
        return res.status(401).end('没有登录')
    }

}

As a side note, you probably should pull your jwt expiry checking out of that route handler and into its own middleware (or better yet, adopt Passportjs), for better reuse. 附带说明一下,您可能应该将jwt到期检查从该路由处理程序中取出并放入其自己的中间件(或者更好的是采用Passportjs),以便更好地重用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用MongoDB ObjectID进行主干同步/保存 - Backbone sync/save with MongoDB ObjectID 如何在 Flutter 中使用 MongoDB 的 objectId 访问引用数据? - How to access a referenced data with objectId of MongoDB in Flutter? mongoose save() 不保存数据,而是使用 objectId 的空数组 - mongoose save() not saving data but empty array with objectId Mongoose + MongoDB-尝试使用POSTMAN保存后,强制转换为ObjectID的值失败 - Mongoose + MongoDB - Cast to ObjectID failed for value after try save with POSTMAN 对于相同的地理数据,MongoDB 在 .save() 和 .findOneAndUpdate() 上的不同行为 - MongoDB different behaviour on .save() and .findOneAndUpdate() for same Geo data 在猫鼬/节点中保存数组时如何为每个元素生成一个objectId? - How to generate an objectId for each element when saving an array in mongoose/node? 当猫鼬模型被新建时,有没有办法自动生成 ObjectId? - is there a way to auto generate ObjectId when a mongoose Model is new'ed? MongoDB / ExpressJS - 当ObjectID包含在变量中时,通过_id删除文档 - MongoDB/ExpressJS — remove document by _id when ObjectID is contained in a variable 尝试解析MongoDB ObjectId时出现AngularJS语法错误 - AngularJS Syntax Error when trying to parse an MongoDB ObjectId MongoDB使用Node.js保存数据 - Mongodb Save data with nodejs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM