mongoose schema 数组这样设置schema为什么老出错

& mongoose 定义自增字段 :PinterSpace | 分享与学习的次元
mongoose 定义自增字段
使用过mongoose数据库的同学都知道 mongoose 默认是没有像其他数据库拥有一个自增的 id 字段。
那么如何实现呢? 有个mongoose-auto-increment, 使用 npm install mongoose-auto-increment 安装好。
步骤1 首先需要把连接数据的方法复制给一个变量,这里是connection ,接着使用exports.mongoose.connection =
var connection = mongoose.connect('mongodb://localhost/book', function(err){
console.log('连接失败');
console.log('连接成功');
var connection = mongoose.connect('mongodb://localhost/book', function(err){&&if(err){&&&&console.log('连接失败');&&}else{&&&&console.log('连接成功');&&}});
步骤2 在数据库定义页面,引入模块
var mongodb = require('./mongodb');
var Schema = mongodb.mongoose.S
var autoIncrement = require('mongoose-auto-increment');
//自增ID 模块
autoIncrement.initialize(mongodb.mongoose.connection);
var mongodb = require('./mongodb');var Schema = mongodb.mongoose.Schema;var autoIncrement = require('mongoose-auto-increment');&& //自增ID 模块&&&&autoIncrement.initialize(mongodb.mongoose.connection);&& //初始化
步骤3 设置 mongoose-auto-increment
BooksSchema.plugin(autoIncrement.plugin, {
model: 'Books',
//数据模块,需要跟同名 x.model("Books", BooksSchema);
field: 'bId',
startAt: 1000,
//开始位置,自定义
incrementBy: 1
//每次自增数量
BooksSchema.plugin(autoIncrement.plugin, {&&&&model: 'Books',&& //数据模块,需要跟同名 x.model("Books", BooksSchema);&&&&field: 'bId',&&&& //字段名&&&&startAt: 1000,&&&&//开始位置,自定义&&&&incrementBy: 1&&&&//每次自增数量});
我的一个实例
var mongoose = require('mongoose');
var Schema = mongoose.S
var objectId = Schema.Types.ObjectId;
var autoIncrement = require('mongoose-auto-increment');
//自增ID 模块
autoIncrement.initialize(mongoose.connection);
var BookSchema = new Schema({
name: String,
author: String,
category: [{type: objectId, ref: 'Category'}],
from: [{type: objectId, ref: 'Users'}],
image: String,
press: String,
isbn: String,
page: {type: String, default: '未知'},
sky_drive: String,
//网盘地址
description: String,
//内容简介
press_time: String,
//出版时间
remark: String,
average: { type: String, default: '0' },
//豆瓣评分
reply_count: { type: String, default: '0' },
create_time: { type: Date, default: Date.now },
//创建时间
update_time: { type: Date, default: Date.now },
//更新时间
pv: { type: Number, default: 0 },
//浏览次数
dv: { type: Number, default: 0 },
//下载次数
thanks: [{
//感谢次数
user: {type: objectId, ref: 'Users'},
username: String,
at: {type: Date, default: Date.now }
visitors: [{
user: {type: objectId, ref: 'Users'},
username: String,
gravatar: String,
at: {type: Date, default: Date.now }
BookSchema.plugin(autoIncrement.plugin, {
//自增ID配置
model: 'Books',
field: 'bid',
startAt: 1000,
incrementBy: 1
BookSchema.pre('save', function(next) {
if (this.isNew) {
this.create_time = this.update_time = Date.now()
this.update_time = Date.now()
module.exports = BookS
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
var mongoose = require('mongoose');var Schema = mongoose.Schema;var objectId = Schema.Types.ObjectId;var autoIncrement = require('mongoose-auto-increment');&& //自增ID 模块&&&&autoIncrement.initialize(mongoose.connection);&&&&&&&&//初始化&&&&var BookSchema = new Schema({&&name: String,&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&//名称&&author: String,&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&//作者&&category: [{type: objectId, ref: 'Category'}],&&&&&&&& //分类&&from: [{type: objectId, ref: 'Users'}],&&&&&&&&&&&&&&&&//贡献人&&image: String,&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& //封面&&press: String,&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& //出版社&&isbn: String,&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&//ISBN&&page: {type: String, default: '未知'},&&&&&&&&&&&&&&&& //页数&&sky_drive: String,&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& //网盘地址&&description: String,&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& //内容简介&&press_time: String,&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&//出版时间&&remark: String,&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&//备注&&average: { type: String, default: '0' },&&&&&&&&&&&&&& //豆瓣评分&&reply_count: { type: String, default: '0' },&&&&&&&&&& //评论数&&create_time: { type: Date, default: Date.now },&&&&&&&&//创建时间&&update_time: { type: Date, default: Date.now },&&&&&&&&//更新时间&&pv: { type: Number, default: 0 },&&&&&&&&&&&&&&&&&&&&&&//浏览次数&&dv: { type: Number, default: 0 },&&&&&&&&&&&&&&&&&&&&&&//下载次数&&thanks: [{&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& //感谢次数&&&&user: {type: objectId, ref: 'Users'},&&&&username: String,&&&&at: {type: Date, default: Date.now }&&}],&&visitors: [{&&&&user: {type: objectId, ref: 'Users'},
username: String,
gravatar: String,&&&&at: {type: Date, default: Date.now }&&}]});&BookSchema.plugin(autoIncrement.plugin, {&&&&&&&&&&&&&& //自增ID配置&&model: 'Books',&&field: 'bid',&&startAt: 1000,&&incrementBy: 1});&BookSchema.pre('save', function(next) {&&if (this.isNew) {&&&&this.create_time = this.update_time = Date.now()&&}&&else {&&&&this.update_time = Date.now()&&}&&&next()});&module.exports = BookSchema;
大家都看这些
- 4,361 views - 3,059 views - 2,478 views - 2,232 views - 2,128 views - 2,080 views - 1,855 views - 1,758 views - 1,406 views - 1,401 views使用Mongoose定义的Schema包含数组,保存的时候出错CastError: Cast to ObjectId failed for value “[object Object]”_问答_ThinkSAAS
使用Mongoose定义的Schema包含数组,保存的时候出错CastError: Cast to ObjectId failed for value “[object Object]”
使用Mongoose定义的Schema包含数组,保存的时候出错CastError: Cast to ObjectId failed for value “[object Object]”
我使用Express.js和mongoose创建一个类似博客系统,一篇文章有若干个类别。
文章的Schema定义如下:
var mongoose = require('mongoose'),
Schema = mongoose.S
var ArticleSchema = new Schema({
created: { type: Date, default: Date.now},
title: String,
content: String,
summary: String,
categories: [{
type: Schema.ObjectId,
ref: 'Category' }]
mongoose.model('Article', ArticleSchema);
类别的Schema定义如下:
var mongoose = require('mongoose'),
Schema = mongoose.S
var CategorySchema = new Schema({
type: Schema.ObjectId,
name: String,
subs: [CategorySchema]
mongoose.model('Category', CategorySchema);
保存文章的代码如下:
exports.create = function(req, res) {
console.log(req.body);
var article = new Article(req.body);
article.user = req.
console.log(article);
article.save(function(err) {
if (err) {
console.log(err);
return res.jsonp(500, {
error: 'Cannot save the article'
res.jsonp(article);
保存的时候,这里的输出如下:
// console.log(req.body);
{ title: 'This is title',
content: '&p&content here&/p&',
categories:
[ { _id: '53c934bbf299ab241a6e0524',
name: '1111',
parent: '53c934b5f299ab241a6e0523',
sort: 1 } ],
updated: [ 3 ] }
// console.log(article);
title: 'This is title',
content: '&p&content here&/p&',
_id: 53c93dc5b1c3b8e80cb4936b,
categories: [],
created: Fri Jul 18 :17 GMT+0800 (中国标准时间) }
// console.log(err);
{ [CastError: Cast to ObjectId failed for value"[object Object]"at path"categories"]
message: 'Cast to ObjectId failed for value"[object Object]"at path"categories"',
name: 'CastError',
type: 'ObjectId',
value: [ [object Object] ],
path: 'categories' }
出错就是在Category这个数组的地方。请问这个怎么解决呢?我已经搜索了很多,但是都没有结果,请大神帮忙。
但是我使用几乎相同的代码更新一个已经存在的文章,就不会出现问题,应该不是类型的问题,代码如下:
var mongoose = require('mongoose'),
Category = mongoose.model('Category'),
_ = require('lodash');
exports.update = function(req, res) {
console.log(req.body);
var article = req.
article = _.extend(article, req.body);
console.log(article);
article.save(function(err) {
if (err) {
return res.jsonp(500, {
error: 'Cannot update the article'
res.jsonp(article);
这段代码的输出如下:
// console.log(req.body);
{ _id: '53ca42f418bfb23c1e04df02',
summary: 'tttt',
title: 'tt',
content: '&p&tttt&/p&',
categories: [ { _id: '53c934bbf299ab241a6e0524', name: '1111' } ],
created: 'T10:05:40.183Z'
// console.log(article);
{ _id: 53ca42f418bfb23c1e04df02,
title: 'tt',
content: '&p&tttt&/p&',
categories: [ { _id: 53c934bbf299ab241a6e0524, name: '1111', subs: [], sort: 0
created: Sat Jul 19 :40 GMT+0800 (中国标准时间)
这样就能正常工作,这是为什么呢?
你在保存的时候categories里面应该放Category的ObjectId,而不是完整的内容。
title:"This is title",
content:"&p&content here&/p&",
categories: [new ObjectID("53c934bbf299ab241a6e0524")] // 这里应该是 oid 实例,而不是整个对象
题主后面那个执行正常的例子应该是因为req.article.categories里存的已经是Document 对象了,所以恰好跳过了 oid(ObjectID)检查。
详见 mongoose 3.8.13 源码 lib/schema/objectid.js 81 ~ 91 行。
if (value instanceof Document) {
value.$__.wasPopulated =
// setting a populated path
if (value instanceof oid) {
} else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
throw new CastError('ObjectId', value, this.path);
添加你想要问的问题
PHP开发框架
开发工具/编程工具
服务器环境
ThinkSAAS商业授权:
ThinkSAAS为用户提供有偿个性定制开发服务
ThinkSAAS将为商业授权用户提供二次开发指导和技术支持
让ThinkSAAS更好,把建议拿来。
开发客服微信node.js - mongoose schema creation - Stack Overflow
to customize your list.
Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
J it only takes a minute:
I've just started with mongoose. I have a creation script with mongoose that creates the schemas and db with sample data.
Now I write the actual application. Do I need to create the schema object each time my application runs, or is it already available somehow?
In other words do I need to run this code in every app that uses mongoose to access the db or just the first time:
var Comments = new Schema({
How would the answer change if I have setters/validations/etc?
11.3k1873127
One defines Schema so application understands how to map data from the MongoDB into JavaScript objects. Schema is a part of application. It has nothing to do with database. It only maps database into JavaScript objects. So yes - if you want to have nice mapping you need to run this code in every application that needs it. It also applies to getters/setters/validations/etc.
Note however that doing this:
var mongoose = require('mongoose');
var Schema = mongoose.S // &-- EDIT: missing in the original post
var Comments = new Schema({
mongoose.model("Comments", Comments);
will register Schema globaly. This means that if the application you are running is using some exterior module, then in this module you can simply use
var mongoose = require('mongoose');
var Comments = mongoose.model("Comments");
Comments.find(function(err, comments) {
// some code here
(note that you actually need to register the Schema before using this code, otherwise an exception will be thrown).
However all of this works only inside one node session, so if you are running another node app which needs the access to the Schema, then you need to call the registration code. So it is a good idea to define all Schemas in separate files, for example comments.js may look like this
var mongoose = require('mongoose');
var Schema = mongoose.S // &-- EDIT: missing in the original post
module.exports = function() {
var Comments = new Schema({
mongoose.model("Comments", Comments);
then create file models.js which may look like this
var models = ['comments.js', 'someothermodel.js', ...];
exports.initialize = function() {
var l = models.
for (var i = 0; i & i++) {
require(models[i])();
Now calling require('models.js').initialize(); will initialize all of your Schemas for a given node session.
29.6k263100
You do need to run this initialization code every time you run your app to register your app's Schemas with mongoose.
When your app ends, mongoose does not store your Schema(s). So, the next time you run an app that uses a Schema, you need to register your Schema(s) again.
However, it's fairly easy to set up your app to do so.
Here are two links to code that demonstrates how one can initialize schemas in mongoose. The first is in JavaScript, the second is in CoffeeScript.
The JavaScript demos is just one app.
The CoffeeScript code has two separate apps. The first stores documents with MongoDB, the second finds and displays the documents stored by the first app.
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you're looking for?
Browse other questions tagged
Stack Overflow works best with JavaScript enabled}

我要回帖

更多关于 mongoose schema 数组 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信