• Moogoose实践之:Schema写全很重要,不然会把时间浪费在调错上!


    哎,今天浪费了很多时间在调用Moogoose的update函数上,我有一个很简单的文档结构,类似于:{name: xxx},MongoDB的驱动,我用了Moogoose,我的问题是,我想对该文档,增加一个属性,比如age,那么文档就变成:{name: xxx, age: 16}。相关代码如下:

    NameCandidateSchema = new mongoose.Schema(
            name: String
    )
    
        handleVoterVoteFor: (req, res)->
            voter = req.params.voter
            {id} = req.query
    
            query = {_id: id}
            update = {age: 16}
            NameCandidate.findOneAndUpdate(query, update,  (err, doc)=>
                if err then res.send(500, err)
                else
                    console.log(doc)
                    res.json(200, doc)
            )
    

    问题是,age属性死活插入不到文档中去!白白花了2个小时,终于明白了,Schema里面忘记把age属性加进去了。。。汗!

    那么,假如我想加入一个内嵌的文档,但是Key, Value不定,怎么办呢?举个例子,每个name,大家都可以对他投票,投票的记录放在同一个文档中,是一个内嵌的文档,key是投票人的名字,值是他投的票数,比如,对于puncha这个名字,张三、李四分别投了2票3票,那么该文档可以表示成: {name: 'puncha', votes: {'张三': 2, '李四', 3}}。那么Schema怎么定义呢?

    mongoose = require('mongoose');
    Schema = mongoose.Schema;
    
    NameCandidateSchema = new mongoose.Schema(
            name: String
            votes: Schema.Types.Mixed
    )
    
        handleVoterVoteFor: (req, res)->
            #console.log(req.query.name + req.query.id + req.query.score)
            voter = req.params.voter
            {id} = req.query
    
            queryClouse = {_id: id}
            updateClouse = {}
            updateClouse["votes.#{voter}"] = parseInt(score, 10)
            NameCandidate.update(queryClouse, updateClouse,  (err, numberAffected)=>
                if err then res.send(500, err)
                else
                    console.log(numberAffected)
                    res.json(200, numberAffected)
            )
    

    看到没,要使用Schema.Mixed这个类型。BTW, 这里我用了update,其实和上面的findOneAndUpdate是没啥区别的,



  • 相关阅读:
    Visual Studio Code 上java开发环境搭建
    c++编译时打印宏定义
    git使用
    Let's Encrypt申请证书及使用
    使用docker创建aosp编译环境
    项目中使用protobuf 3.0
    ubuntu14.04 安装mono
    ubuntu14.04 安装apache+mysql+php
    Discuz & UCenter 修改手记
    代码细节重构:请对我的代码指手划脚(四)
  • 原文地址:https://www.cnblogs.com/puncha/p/3876867.html
Copyright © 2020-2023  润新知