gpt4 book ai didi

node.js - 具有唯一模式键的 Mongoose 重复项

转载 作者:IT老高 更新时间:2023-10-28 22:05:32 25 4
gpt4 key购买 nike

我想让关键项目在该集合中独一无二,但我无法正常工作,我在这里发现了类似的问题。

task.js

function make(Schema, mongoose) {

var Tasks = new Schema({
project: { type: String, index: { unique: true, dropDups: true }},
description: String
});

mongoose.model('Task', Tasks);
}
module.exports.make = make;

test.js

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/rss');

var Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;

require('./task.js').make(Schema, mongoose);
var Task = mongoose.model('Task');
var newTask = new Task({
project: 'Starting new project'
, description: 'New project in node'
});
newTask.save(function(err) {
if (err) console.log('Error on saving');
});

mongoose.disconnect();

当我使用 Node test.js 运行应用程序时,仍然会创建重复项。

MongoDB shell version: 2.0.2
connecting to: rss
> db.tasks.find()
> db.tasks.find()
{ "project" : "Starting new project", "description" : "New project in node", "_id" : ObjectId("4f21aaa3d48d4e1533000001") }
{ "project" : "Starting new project", "description" : "New project in node", "_id" : ObjectId("4f21aaa4d9a8921a33000001") }
{ "project" : "Starting new project", "description" : "New project in node", "_id" : ObjectId("4f21aaa57ebeea1f33000001") }

//编辑还是同样的问题,这是我尝试做的删除 db.tasks.drop() 集合重启mongo sudo stop mongodb 并启动mongodb,再次运行程序还是同样的问题,它如何允许索引上的重复数据?

最佳答案

您传递的 Schema 对象可能无法正常工作,因为您将 'unique' 属性嵌套到 'index' 属性中,尝试这样的事情(它按预期工作):

User = mongoose.model('User', new Schema({
firstName: {
type:String,
required: true,
},
lastName: {
type:String,
required: true,
},
email: {
type:String,
required: true,
unique: true
},
address: String,
phone: {
type:String,
required: true,
},
password: {
type:String,
required: true,
set: Data.prototype.saltySha1 // some function called before saving the data
},
role: String
},{strict: true}));

或者更具体地为您的示例:

var Tasks = new Schema({
project: {
type: String,
unique: true,
index: true
},
description: String
});

注意:我不知道你想用“dropDups”参数做什么,它似乎不在 mongoose documentation 中。 .

关于node.js - 具有唯一模式键的 Mongoose 重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9024176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com